0% found this document useful (0 votes)
2K views21 pages

Unit 3 FIOT

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

Unit 3 FIOT

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

ESSAY QUESTIONS WITH SOLUTIONS

1NTROD UCTIONT O PYTHON PROGRAMMING


3. I
What IS Python? Explain the features of Python language.
Q9,
Model Paper-Ill, Q61"1J

l'),(bon
It is a simple, interactive, interpreted object oriented programming language. When compared to other programmm
it is a very robust, elegant and a powerful language.
l~ages. g
features of Python
Object-oriented Programming Paradigm
1,
Python is an object-oriented pro~an~minglang~age, as it sepa~ates data_from logic. Moreover, Python is not only object-
oriented, but also a proper combmat10n of multtple programmmg paradigms.
Easy to Learn
Python consists of very few keywords, simple structure and well defined syntaxes which makes it easy to learn.
Easily Readable
3.
Unlike other programming languages, it does not make use of symbols like ($),· semicolon (;), tildes (~) for accessino
variables, defining code blocks and pattern matching. Rather, it defines a simple and clear code, which is easier for th:
programmer to read. Python language has been designed in a way, that the code written by one programmer can be easil)
understood by the other.

4. Easily Maintainable
Since, Python is simple unlike other programming languages, it does y.ot require much difficulty for maintenance. For
example, for the existence of its code, it qoes not depend on the presence of the programmer at a company. Toe most
important advantage of Python is that, at the time of reviewing a script written very long time ago, the programmer does
not require much guidance from a reference book.
s. Uses Wgb-level Dat~ Structure
. .
Python has been designed in a way, that the programmer does not need to look after the low level details such as, memor)
management. It supports high level data structures such as, realizable arrays (lists in Python), hash tables (dictionary in
Python). As these building blocks are defined in the core language, they are extensively used. This reduces the development
time, as well as the size of the code. Thereby, making the code more simpler to read.
6. Extensibility
Python ·allows the p~ofiammer to code some part of the program in different languages like, C, C++, java and utilize them
through Python code.
7. Portability
Since Python is written in C, it can work on different platforms i.e., the Python applications built on one system, can run
on any other system, with little or no modification. Any platform that.contains ANSI C compiler supports Python. Python
is also independent of the type of archite~ture. · ·
I,• ·Robust
Python is more powerful in determining as well as handling error conditions, through software handlers. It ~uides the
' program.mer, by providing full details of errors, in case of program crashing due to errors. For example, the locatIOn where
the error has occurred in the code, by specifying the filename, line number and function. It also allows the programmer to
take an action for the elimination of the error.
· . . · -fy · th
.The exception handlers in Python are capable of reducing debuggmg blem redirecting the
process, by simp1I mg e ~ro . ' . •t case
ro
P gram flow, performing cleanup or maintenance measure, cIosmg · the 1· t· l cmntly or Just 1gnonng 1 1n
app ica 100 e e0 - · . f the ·error in
'
if ~e. errors covld not be handled properly, Python generates a stack that displays the type and l~catwn ° · '
addition to the location of module that contains the erroneous code. ·
,SPECTRUM flLL-IN-O~E JOURNAL FOR ENGINEERIN~ STUDENTS .
I .I
I
3.6 FUNDAMENTALS OF INTERNET OF THINGS. [JNTU-HYOERAa.,,,I)~
. ~
9. P~esses the Rights of a Memory Manager
O f th ' d 't It If handles all the functionalities re lat
ne o. e mam a vantages of Python progrnmming langungc is tha,l, ! se d the overall development ti ed to
~emoty management. Thereby, reducing the programmers burden. Th1s JO turn r~ uces llle an()
mcludes fewer bugs. ll handles memory management through the use of Interpreter.
10. Interpreted and (Byte) ContpU~ Language
Just like Java, Pytl10t1 is also an interpreted and a byte~com_piled language. That is, it allows theJ.rllogramd mb erpto run the
Y ython 1·s,
Pro d' l ft · ··
. gram trect Y 0111 the source code without performing the comp1lal1on pr~ · process 10 owe
cess · The

(i) It just transforms the .source code into an intermediate form known as, 'byte code'·
(ii) Then translates the byte code into a machine code (O's and 1's)
(iii) And then run it.
• • proper lihkage and loading oflibraries etc ·
The Programmer need not have to worry about the program comp1lat10n,

11. Scalability .
nd th
The term 'scalability' here, refers to ;he c~pability of the programming .language, to accept a _·haoclle e additional
performance required, upon the·addition of new hardware to the system. Unlike other programmm~ langu~g~s, Pyt?on
can expand the code size, by adding new or existing Python elements and reusing the code when reqmred. This ts possible
because, Python has a pluggable and modular architecture.
12. ~ffective Rapi(f Prototyping Tool
Python provides several interfaces to other systems, which makes it powerful and robust enough to prototype_the entire
systems within it, in a very le~s time. '
Q10. Explain the syntax of Python language.
Answer:
Python language defines a very simple syntax. Its·simplicity lies in design choice. There are several ways to represent 1
single program but this leads·to difficulty in learning and using the language. The philosophy of Pythons states that "There is on
and one way to do it".
Since, Python is a non-functional language we. mostly use assignment statement. The syntax is as follows,
,..
,, . ,,

Syntax
name = expression
Here, the 'name is binded to the value of.the expression.
In other programming languages the above line will assign the expression val~e to name.
Thus, python uses -assignment operator to bind a name to data value generated by the expression. If a reference value ·,
. taken in place of expression then the name, will be binded to the existing value.·
Unlike, other programming language name is not bound to particular data type and no type checking is needed to bind th
name to the value.
Identifiers in Python
• Python define its identifier using letters, digits and a underscore. But, the first character of a name should never be a digit
' '

If several names have to be binded different to the same value, it can be done in. single statement as follows '
>>>SI = s2 = s3 = "Hello world"
Here, S 1, S2 and S3 are binded to Hello world string.
>>>print S1

I
>>>print s2
I
j ' >>>printS3 , , •

.
The output of these three,statements is same i.e., Hello world as all three names binded tosamestnng.

WARNING: Xerox/Photocopying of this book Is a €RIMINAL act. Anyone found guilty is. LIABLE to «,ace LEGAL proceedings

• f
. '
.
lVtf C Modtl P•ptr•I, Ql{at
~-- J\t\) s,>llwrm• hos lwo wt sions ' 2 hit nntl htl hit Tlw 1t'I-IJll'\'tlw vcrnlon hnscd ot1 the operating system can be
downloaded
. 1lk\1 thml thl' lwfow hnk .
J il,s11
~1111
https ://www.pyth\m.1Rp,/,h1wnlonds/il•k•llNl'/pytho11,J(14

' •kl'I 'Wtl\lfo,,s ~ ~h M l'Xl'l'lltnbk instullcr' lht M bit opcruting 1-1y11tcm computer or seJcct ' windows
1,,lki ' for ~ }-hit opl'tnting system comp,1tcr with this 'pylhon-3.6.4 and 64-cxc' file will be downloaded.
1<86 executable
~l
UIS•

l),iuhll' dk1' (,n 'p) thon ,J.(1..t-nnd M.1..'xc' Ille. This will displuy a Hotup dialog box.

('Itek the dl'-'ckhox install lnunchc1 1hr nil the u:,crs oml udd python 3.6 to PATIi.

Install Python 3.6.4 (64-bit)


Select Install Now to install Python with default settings, or choose
Customize to enable or disable features .

.,. lnstall'Now
C:\User~\CG3\AppOata\~oca~ProgramMython\?ython36

Includes IDLE, PJP and documcntat1on


Creates1hortcut~and file mociations

_. Customize installation
Choose location and features

python
r,, [j ln~tall launcher for all users (re~mmended)
windows i'.l] Add Python 3.6 to PATH

4, Click on Install Now. This will show a setup program window.


, --·- - - - -- -- --- ---------- -----~ ~ ~
., ~ '~~
-- - ---- - - - - - - - ---- - -- - - --- -

Setup Progre~s

Installing:

Python 3.6.4 Standard Library (64-bit)

python
f,
windows Cancel

SPEd'ROM ALL-IN-ONE JOURNAL FOR ENGINEERING STUDENTS


3.8 . FUNDAMENTALS OF INTERNET OF THINGS [JNT
. U•HY DE~A ~
5. ()nee tht.' instnllnlil)n compl etes n dialog b . ars showi ng the message 'setup was succes sful'. Final~y, click
t)l ,
button . ox .1ppc on c\
. °St

Setup was successful


I •

Special th~nks to Mark Hammond, without wnose years of


free~ shared Windows expertise, Python for Windows would
stlll be Python for DOS.

New to Pythonl Start with the !.l!llioi.11,11oci.iil and


®llill.\®fillQ!J,

See \\'ruiJlr.!fil'!' in this release.

·python
for
windows
012. Define control statements. Discuss about
Answ er:
Decision Struc tures / Control ~tatements
if statement. -
Mod~ Paper-II, 06<•)

Decis ion struct ures or Contr ol statem ents are the statem
ents that allows the progra mmer to specif y the next statem
must be execu ted depen ding on some condit ions. · ent that
'
if State ment
The if statem ent contai ns the follow ing three compo nents,
(i) The Keyword 'if'
The 'if' clause is execu ted, only if the expres sion is
true otl)erwise, execu tion starts at the next statem ent
code. ·
follow ing thi
(ii) An Expression or a Cond ition
An expre ssion is tested for its truth value. If the expres sion
evalua tes to non-z ero or Boole an true then the code is
execu
Syntax
if expres sion:
Statei nentl
Statem ent2
Multiple Conditional Expressions
To provid e multip le condi tional expres si9ns, or to perfor
m negati on of expre ssions in the if statem ent, Boole
and, or and not are used. an operaton

ExamP.le
if not valid or (coun t< 0):
print "Inva lid input"
(iii) The Code
Single State ment Code
If the code of if clause conta ins only a single statem ent, it may
be writte n on the same line as the header statement.
ExampJe
if i = = I : print "Welc ome to Python"
Although it is easy to write tqe .code in one line, but it is difficult to read.

WARNING: Xerox/Photocopying of this book is a CRIMINAL ~ct. Anyone found guilty


is LIABL E to face LEGAL ~in gs.
'0"1f~3:__....--....,,_;;.........,.._______ ___~ - - - - - - - - - - - - - - 3.9
---------
~
ii•,nple .
i days = int(inpul("How ntany dnys docs leap ycnr contaii1 ?: "))
if days == 366:
print("You are right!! 11) •
Oittpnt
i{j. l!jM:
filt_!~ft2!~~:~u~ _Op~~~!indow . H~1> _ -··· ~ .. __ ~
__. ~SIAR!: C: /tlsers/ref-b/AppData,?ocal/ Programs/Pytbon/Pythor:38-32/
N n:ar.y days does leap year conx.aint: 366
.:.fi.xarrp:..e. p:; === 1

_
·• ,..ht •,
~ ate 1.~.
1'
..
,..
p·>> I . . __, ~ ,
Ln; 188 Col: 4
~o1scuss about If-else statement.

--1
if...elSe Statement
Ifelse statement is used to execute a set of statements if the condition is true otherwi
se it executes,another set of statements.
1be syntaX of if...else is as follows, ·
if condition :
# statements
else:
# statements
The if is succeeded by a copdition and a set of statements. If the condition
is true the statements following if condition
will be executed.
Jfthe condition is false the statements following else will be executed.
Enmple
a= int(input("Enter a number : "))
ifa%2 =0:
print("The given number is an even number")
else:
print("The given number is an odd number")
Output

.. RESIART: C: /Users / ref-b/.AppDa ta/Loc al/Prog:rams/ Pytr.o:JPythor.3c-32


/ ife:3e!xarr.p.:..e. ~1· = ,.
Er-ter a number: 15
foe given nurr.ber 1s an odd r,urr.ber
>» I
. ·-•·· -~----- -- ·--- -- -·- "

Ln:192 Cor. 4
1bis In the above examp~e initiall~ t~~ input is accepted from_user !nto a. The value of 'a'
Ifthe~ r generates remainder of d1V1s10n operator. If the remainder 1s Othen the :°
is div~de~ by 2 ~s~ng operator.
statement follow mg 1f cond1t10n 1s executed.
remainder is non zero then the statement following else will be executed.

SPECTRUM flLL-IN-ONE JOORNflL FOR ENGINEERING STODENn


r 3.10

.
Q14. Give• brief Introduction about repetltloh structure.
"nswe ,· :
.
FUNDAM~NTALS OF tN
reRNET OF THINGS [JNTU+tYoe~~
.

t · k repeatedly. For example ,


Mode1 Pa
~

Thc me as
progrmnmcrs sometimes need to write thb code that per forms thebest sa · t write the code t , con31.
approach is
program to calculate t Opercent sales conunission for several sales people. One o o ca1c~1-
sales person commission and then repeat the same code for every sales person. ~

Sales = float (input ('Enter sales a1nount:'))


= float (input ('Enter commission rate'))
Com = Sales • rate
print"" ('Commission$', fom1at(commission, ', .2f', sep • ')) d Writing of long sequence of stat
. ffth bo . , d 1· t1 ofsameco e.
. ea ve c~e ls repeated for every person then there 1s up ,ca on .ons has to be done several times.. Th
wdl be time consunung. If the duplicated code need to be corrected then correctl .
e best w
tructure which makes the cornp
repeatedly perfom1 an operation is to write the code the once and then place the code m a
~ly called as loop. There are two ti
repeat required nUU1ber of times. This is possible with a repetition structure mo~~ comm~o
lled loop uses true/false conditi'
of loops namely, condition-controlled loop and count-controlled loop. A con.dit,on c:r
of times. In python, while statern!
-control nUU1ber of times it repeats. The count controlled loop repeats for specific num
. a condition
. . controlle II d p
used to wnte . the co unt contro e 1oo ·
d loop and for statement is used to write
l. Condition Controlled Loop: The while Loop
' while
· ,· .. 'f h d' ·
1s the first conditional looping statement in python ..In ,if
. statemen he code is executed 1 t e con 1tion is
t, t
whereas, in while the code is executed in a loop until the condition becomes false.
Syntax
while condition
, I
Code to be executed.
· .the whife
The code m • loop,
. gets executed repeated · 'untt··1 the expression (condition) becomes false (Boo
number of times,
value false).
Whenever a user does know the number of times a loop n~ed to execute, it is better to use
the 'while' statement.
Eu.mple ,.,
x=6
while (x>=l):
print("The value of.xis: ",x)
x=x-1
Output
1
fu ~111.-.i1 Jf8. ..,(l l\1~ ~~·' '%~ %-? ~ c~r s -1~
}dit .., SheU ~·
,. ,Frle, Oebu!! . Options .. \_"lindOIN ... ':{elp . ......... ..· -···· . . . ==~~~
••·• RESTART : C : /CTser.!!! / ref-b/ AppData/ Lo c a l. / Prcgram~ . -··· ...... ·······- .
/ P ~rthon / P y t hon3S - 32 /w!--± l.e:Ex ar:-.p .l e • PY == ._
T h e ~.ra l.u e o f x l.~ : 6
T~ e v a lu e o f x i a: 5
Tl:: e v a .lue r:, f x . !.3: 4
, T~e v a lu e a % x is : 3
T~ e v a-1..ue o f x l.S : 2
Th e valu e o f x i s: 1
»> I
Ln: 211 Col: 4

With each iteration, the condition in the while loop is checked, whenever condition becomes
false control comes o
the loop.
2. Count Controlled Loop: The for Loop
The for statement is a powerful looping construction in Python. The looping mechanism
in for statement is applied, o
the sequence members. for statement calls the next() ,nethod of an iterator and ends when
Stoplteration except-ion is raised.
comprehensions and generator expressions als~ uses 'for statement'.
Syntax
for var in <object> :
<statements>
To repeat the code in the/or loop, each time the iteration v¥iable is set to the current element
of the object.
WARNING: xerox/Photocopying of this book is a CRIMINAL act. Anyone found guilty is LIABLE to face LEGAL proceedings.
3.1 1
of for Loops
1rsrs
Used "'1th Sequcncl' l)·pes
til
8115 tc Usage
tor spam in 'student':
print(C'urrcnt letter:', spmn)

output

Python 3.8.5 Shell


Edit Shell Debug Options Window Help
.,= ~S!AF.7: .: : /Dse :::s / :::ef-b/ AppJ:;a ta/
Loc al / P:og :arr.s / Pyt; ,on/ Pytr .or.3:
c~: : e~t : et~ er ~ s ~32 / f or-b a 3 .:.c . P"l === ,.
:~:::=e=t :et te:: : t
~~~:-e!: t :ett e =: ~
c~:~ e~t :ett e r : d
.:,.:::e~::. :et t e~: e
c-.:::::::e:-.::. :et te:::: ..
: ~::::e~t :et te:: : t
L
L~ 19 Col:4
The iteration variable 'spam', always cont
ains only a single character'when iterating
in debugging of sequences in the for loop over a string. This construct is useful
.
(rl) Iterating by Sequence Item

Example
chocolates= ['Snickers','Cadbury', 'Lacto']
for x in chocolates:
print(x, "chocolate")

Output

{} Python 3.85 Shell


File Ecfrt Shell _D~ug _Op!iom \t'.'indow

3~:cke=s c~oc c:.a t e


:adl:;.:.:::~· c:.ccc:.a"Cre
:..ac~c c:..ccc :..ate

Ln:25 Col: 4
For each iteration in the above example, the
list is iterated and the variable 'x' contains
the list elements.
(ill) Iterating by Sequence Index
Example

arrayelements = ['table', 'chair', 'pen', 'pen


cil']
for x in range(len(arrayelements)):

print(arrayelements[ x])

SPECTRUM fill-IN-ONE JOURNAL FOR ENG


INEERING STUDENTS
IT."'l
I' '
I
3.12
Outp ut
tf~_,,.u ~,11
. ~.
Fnt Edit Shell

I
i.t.r-; rMr 1
t nlil~
t:htll!
I l-"'n
I e-~ < l
>" ' I
Ln: 31 Co~ 4

Herc, /en( ) and mnge( ) arc the built-in functions


·, () ·
,en gives the total ·number ol,clements in the tuple und range(), • h , t , l sequence to iterate over tuple el
provid es t e ac ua Cllitr~
>>> len(array clements)
4
>>> range (len(arrayclcmcnts))
fO, 1,2,3 ]
015. Write the basic style guidelines.
Ans wer:
The basic style guidelines for python are as follows,
l . Comments
2. Indentation
3. Documentation
4. .Selecting identifier names.
I. Comments
Comments should be use9 in programs to provicj.e information
about the function that a program is going to perform i.e
the logic used and the process adopted. Comments should
be clear, short and convey meaningful messages. They incre]1
program readability and save time of others who use the progra
ms.
2. Indentation · .
The spaces left while sta~ing a new paragraph is called indent
ation. Four to six spaces are ideal for indentation while I
than three are bad and more than seven spaces are wastage
of resources. Tabs can also be used for indentation but spaJ
should be preferred.
3. Documentation
In python, documentation strings can be retrieved dynamically
using a variable named _doc_. The attribute obj_obj._doc
used to access first unassigned string in a class or function
declaration. Here, obj refers to module, class or function name
4. Selecting Identifier Names
Selection of identifier names must be shqrt in length and
meaningful. Modern computing storage does not hinder
of the name however, short name s are preferred. len
Q16. Explain how to write and execute a prog
ram•in python.
Ans wer:
A python program can be executed in three different ways;
they are,
(a) Using python's command line window
(bJ. Using python's fDLE graphics window
(c) From system prompt.
(a) Using Python's Command Line Window
This is an interactive mode where a progra,m can be typed
in one line at a time. PVM will execute it.
❖ Open the python's command line.
❖ ·rype the desired program besid e»> symbol (python promp
t).
❖ Result will be displayed when the user type the last line
of program and clicks ·Enter button.
WARNING: Xerox/Photocopying of this bpok is a CRIMINAL act. Anyon~ found guilty
is LIABLE to face LEGAL proceedings. ,
, uNlf-3 --~~~=---------------- ------~3:.:,:.1::3

tlsln~ PyChon;~ IDLIJ: Grnphks Window


ctkk Oil Python's II)) .E icon
lf() w fik and click on New File (Clrl f N) oplion in IDLE window
L• Pytho;,-;,~.~ Shell - - - - - -- - - -
D 1
Filt Edit Shell Debug Oplioni Window Help 1
I
New FM Clrl ► N eb, Dec 19 2017, 06:04 :q5) (MSC v. 1~00 32 bit (Iotel)f or.
Open .. , Ctrl+O
Open Module... All+M " or "license()" for more i nforn,.ation.
R"enl Files
Module Brows et Alt+ C
Path Browser • I

Save Ctrl+S
Save As... Ctrl+Shift+S
Save ~opy As... Alt+Shift+S

Print Window Ctrl+P

3.
Anew window will open. Type the program in it.
, ~ ,,.• q ·r ;:- •r h·.!i r------------------ - - D_.J;:..___, !
X t !
0

• , .,.. ,, <, , [~ 'Untitled•


File Edit Sheil [lej
Python 3 . 6 .~ (v'_F.il·~-- E~it Format Ru". _. 9.P!~°.n.:_ ~i~~~~----H_elp_ _ _ _~ - - - - -
win32 p=a · A

Type "copyright q=4


>>> r=p/ q
gnnt( »h,.nlr.":",r);

4. Save the file.


L~ *Untitled* □ X
. ~L: fdit FQrmat Bun Qptions Window .tfelp
New File Ctrl+N
Open ... Ctrl+O
Open Module... Alt+M
Recent Files .
't ' . Module Browser Alt+C
Path Browser

' Sil'tP.: Ctrl+S .


Save As,,, Ctr!+ Shj~+ S
Save Copy As... Alt+ Shift+ S

Print Window Ctrl+P,

Clo~e Alt+F4
fxit Ctrl+Q

SPE~OM fill-IN-ONE JOORNfll FOR ENGINEERING STODENTS


3.14 NTERNET OF THINGS [JNTU-HYDERA
FUNDAMENTALS ~ F I . ~~~
5. Go to Run nnd sdcd R,.m M{Hhik-.
fl X

6. Result will be displayed in o 11~v window._ , x


'

[tP}1honlWhr!I
[lit ta,1 11,!JI Q,bug Qp\ion1 Wmdow u,1p

111n32
rl'Pt 'cop~Iight", 'ondi~s• or 'H0en1, I)' !or more lnton1.,11!on,
.,
~ ,
0
J
P)>th9n 3.6,4 (v3,6, ◄ tdl!ec,b, D~c H 20J7, 06104149) (MSC v.1~00 J~ bit (Intel) on
1
·, ) ~

--•--•-••...•-• RESTART: Ct/Uatr.!/home/~sktop/b,py ........ -••--.._.•


R,~ul~• l ,Q
}\~

(c) From System Prompt


Wn·tin·g and executmg
· the python scnpts
• ,1s an easy process: lmllally
·· type "P. Ylh on "or
. "Python 3" at the command pro
to access python, With ~is even python R.EPL (Read-Eval-Print-Loop) gets opened. To exit from REPL type Ctrl-D, Folio\\'
below steps to write and rw1 a python s~ript.
1. · Create a new file with name MyScript.py.
2. Type the below code in it
tr~;~~;,.·"-
r~e Edit Format V!ew Help
#! / user /bi'n/python
t
t X=2
f y=6
! sum=x+y
prirrt (sum)I

' ◄ \

3. Save the file with .py extension. Even text editors such as notepad or notepad ++ to write the code and press ctrl +
exit
4. Without making the file executable it can be run by navigating the location of the script and then by typing MyScript.
5. MyScript.py can be made executable by typin~ chmod +x MyScript.py at command prompt.
6. To run the script type at command prompt.
C:\>python MyScript.py
This command will call the compiler to convert the file into byte code. This byte code will converted to machine code a
the processor will execute this machine code.
Output

Miu·o~oft \/indu11~ IUe1.•sion 6 .1. 7601]


Gupy1· i'.Jlir, 1 c) 2009 l1it1•0:;oft Co1•po1•c1t ion. All l'ights 1•eserved.
c:,LJ~cr~\CUl>cd ..

i C:\.>cd JJytlwr,

J;:\p1;tho1r>µytl,on Ny8c1•ipt.py
8
G; '.pyt lion)

~ARNING: Xerox/Photocopying of this book Is a CRIMINAL act. Anyone found guilty is LIABLE to face U:GAL proceedings.

(
I
""'r-3 __ __ __ __ __ __ __ __ __ 3.15
oefln& operator. Describe different types of
Q1 1· perators supported by Python with an example
(II) 'l'1·11r Olv1!1lon (/)
0
tor each. 111 lhc Tntc IJi vi!lioti Oprn,t ion, the quo tient or res ult
ohtn lnc<I wi ll he the Hcltiol vuluc, irrcs pcclivc of the
Model P11per-l, Q7 oprn_'fll1d lypt'S, Thill type of division opcrntio11 can be
,4it8~r:
poi formed, only whc11 llw ' from fu1 11rc lm porl di v1sio11'
operstor dirllcliv c is defined.
An operator cun b~ defined ns a symhol which 11crfonn
ltxum1>lc
opcl'3ti.ons such as mn1hcmaticnl, logical 1111d other
,r. ,
1
~111\;
s:,ipulations ~sing one or more opcrnnds. Python supports, >--.-:, from •future- import di vision
11 nun,bl:r ot opcr.1tors. >» 25/2
,srsc
~ of Operators · 12.5
'l)r -
There are three main different types of operators
>>> 25 .0/2.0
..,.,rted by Python. They are listed below,
$t1rr~· 12.5
. Arithmetic or numeric operators
1
(iii) Floor Dl~ision (//)
n. Comparison/Relational operators
In the floor division operation, the fractions obtained
JU. Lo~ical operators. in the quotient are always truncated and rounded to the
Arithmetic or Numeric Operators smallest whole number which is on its immediate left
1. on the number line.
The numeric type arithmetic operators that are supported
bj python are listed below: Example
1. Division(/,//) >» 25//2

2. Modulus(%) 12

3. Exponentiation (**) >>> 25.0//2.0

4. Addition (binary(+) operator) 12.0

5. Subtraction (binary(-) ope;ator) 2. Modulus(%)

6. No change (Unary(~) operator) The computation of modulus is different for different


numeric types.
7. Negation (Unary(-) operator).
❖ The modulo of two integer numbers is the
t. Division(/,//) remainder of their integer division.
~ere are three different types of divisioq operations, . Example
(i) Classic division 17%3 = 2
(ii) True division (/) ❖ The modulo of two floating point numbe rs is
obtained using the following formul a.
(iii) Floor division (//).
. 'd d ( th fl ( dividend ) . . )]
(i) Classic Division [d 1v1 en - ma . oor divisor * d1v1sor
In the Classic Division Operation, the quotient or result
obtained will have the same type as that of the operand ❖ The modulo of two complex numbers is obtained
involved. That is, if integer type operands are involved, using the following formula.
then t~ classic division operation returns an integer type
by truncating the fraction. Similarly, for floating point
operands, it returns the actual floating point quotient.
. :d d (
[d 1v1 en - math . floor
(( dividen )ll
div.isord } rea1t,I, d'1v1sor
• .

Example 3. Exponentiation (**)


>» 25/2 The exponentiation operation, detennines the powe~ of
a numeric type. The binding between the exponentiation
12 operator and its left operand is more tighter than that with
»> 25.0/2.0 unary operators (+, - ). Whereas, the binding between the
exponentiati0n operator and its right operand is less tighter
12.5 than that with unary operators(+,-).

SPEaRUM ALL-IN-ONE JOURNAL FOR ENGINEERING STUDENTS ·


reRNET OF THINGS (JNTU-HVoe~l\ti.
3.16 FUNDAMENTALS OF IN ~
Enmplcs
>>>2.. S # 2 power S
32
, 18
. • ht r rhan with '- '
# lei\ bindhtS with •0 tig c

. . h , , more tighter
# Mukc11 lcfl bir1d111g wit -
- 32
'th••••
>>>2.0 •• - 5.0 # Righi binding wilh ,_, is tighter than w, .
. d t egativo powers
fl Integers cannol be raise O n '
Tmceba..:k(innennost lost);
File"<stdin>'', line l \n?
VnlueError:intcgcr to the negative power
. edence is given below.
The list of all numeric arithmetic operators in the highest-to-lowest order of prec

. S.No. Operator
.
Syntax Function

1. •• expl •• exp2 expl power exp2 (tighter binding to its left)


2. + (unary) +exp Keep sign of exp, unchanged
3. - (unary) -<exp Negation of exp (or) change sign of exp to ,_,
4. •• exp I ** e_xp2 exp! power exp2 (tighter binding to its right)
s.. • exp! * exp2 Multiply exp I and exp2
6. I expl/exp2 Divide exp I by exp2. This division can either
be a classic or a true division ·
7. II expl // exp2 Divide exp I by exp2. This division can be only
a floor div.ision
8. % expl % exp2 Module of exp I divided ~y exp2
9. · +(unary) exp]+ exp2 Add exp 1 apd exp2
JO. -(unary) exp) -exp2 Subtract expl and exp2 ·
' .
4. Addition (Binary(+) Operator)
The addition operator is used to add two operands and generate sum of them as the result.
Example
>>>65 +60
95
>>>65.4+i6.2
81.6
5. Subtraction (Binary(-) Operator)
The subtraction operator is used to subtract two opera_nds and generate the difference between them as the result.
Example
' >>>32-10 ""
20
>>>16.8-4.2

.1 12.6

WARNING; Xerox/Photocopying of this book le a CRIMINAL act. Anyone found guilty is LIABLE to face LEGAL proceedings.
r'....rr. s . 3 . 17
~ Ch•DI" (Unary(+) Operator)
~ - 11'C no change (unary(+) opcmtor) is used before n vorinblc hut the value of it docRnot change lf thc value is positive it
~oins positive ond ifthe vnlrn,' is negative it rcmoins nc~ativo. ·
g11111ple
>:;-,;,,~ 5 '
:!:f

~;,,:>print (- x:)
-5
;,,>'>X == S
;,-~>print (x)
s
Negtdon(Unary(-) Operato1·)
Una'-Y lll~~s operator_ is re~resent~d by the symbol_ minus (- ). It_is used before a variable to make its value negated. That
is the pos1t1ve value of a vanable will become negative and negative value will become positive when this operator is used.
Etample
>>>X:::: 5
';;-;>>print (- x)

-5
>>>n=-5
>>>n=-n
>>>print (ri)
5
E1amples

;j >» 2-./2
; :2. 0
1
' »~ 6 .~/
- ' 2 .;;-
1 2 · "'
-1 » > 25/ /2
!- -
l ... '
~ ~» :Si2

1;» S.. 6
7 2'?
::.>> -2---e
6
, >>> 3.5•• --:-6. 0
J o.001s 1s9~:02~11eto1 g
l~~>.L . ----·- •---·
Ln: 25 Col: 4 >
[ Comparison/Relational Operators
These operators compare only the data values of the participating objects. The comparisons perfonned are based on the
sign and magnitude for numeric values, whereas a lexicography (i.e.,) alphabetical order is followed, in writing dictionaries for
suings. The comparisons result in either Boolean -True or False values.
lhe list of standard type value comparison operators in highest-to-~owest precedence order is given below,
Operator Syntax Determines
< exp_l < exp2 expl is less than exp2
> exp]> exp2 exp 1 is greater than exp2
<= exp]<= exp2 expl is less than or equal to exp2
>= expl > = exp2 exp l is greater than or equal to exp2
== expl = = exp2 exp l is equal to exp2
!= expl ! = exp2 exp l is not equal to exp2

SPECTRUM AU.-llt-ONE JOURNAL FOR ENGINEERING STOPENTS


3.18 ERNET OF THI NOS [JNTU .. HY[)t-b
FUNDAMENTALS. OF INT . ~11~,
..
E,ampl\'s ~

'~~~M
N~ td\t ~ti! ~v9 Opti~M Winttow Htlt' ' ___.. ______...

~'> ~~~: !• ~•~j


l"4l~e

~>> t - ". >


:~,t~e
>>' I
Ln: 4l Col:4

Ill. Logical O~rator


The.se l)pt'rators neg.are or link two or more expressions.
The list of standard type logical operntors in highest to lowest precedrncc order is giwn
bdow:

Op~rator Syntn Determines


not not exp negation or logical NOT of exp
and e.:\l) 1 and exp1 conjunction or logical AND of exp I and exp2
or expl orexp2 disjunction or togicol OR of exp I and exp2
Examples

>>> => 3.02


=~e •
>>> ~~: (rr: = S.2~}

>>> (:::>3.02 ) ~- (~<300)

>>> :::>3.:~ ) -· (n>3~0)


:::-..:.~
>>> --=~ (Ir. :.: ~·
:'=:.:e
>>>
Ln: 53 Col: 4

018. Explain the various datatypes In python.


Answe r:
Model Papt
Datatyp es in Python

The various data types supported/used in Python are as follows.


L Numeric dalatypes
2. String datatypes

J. List dacatypes
4. Tuple datatypes

5. Dictionary datatypcs.

WARHJHG: xerox/Photocopying ofthls book ls a CRIMINAL act. Anyone found guilty ls LIABLE to face LEGAL
proceedin gs.
~,r-3 3.19
~ Nil••·
... erk Oatat\,f)t'S
.
(Iv) <'ontplex
t, ,ric d,1tntypts are tlw immutuhlc dntutypcs i11 ( 'omplcx datalypc is used lo represent complex integers.
7'11Hlll . ,
stores the 1~un,c-nc vulucs. Python suppot Is vnrmus It ,·011si1its of two parts Hwt is a real part and an imaginary
11
111thtl~·. l datat)l)CS hkc, purt. This dalalypc is usually represented as a 1- hj, in
frt~ n
11
11111
') 1n1eger which 'a' is the real part (which can either be a int or
(1 • noat vnluc), bj is imaginary part (where b can take either
Floating pomt
tii) int or float vnlue andj denotes square root of- l ).
(iii) 8tk1knn Syntax
(i' ) complex.
To declare any variable as complex, the following syntax
integer is used,
(il m-•r datatype is used to store signed numeric values.
variable_name = complex(a, b)
lotee- .
doe.s not haYe a dec1ma
. I pomt.. 1
ntegers are usua II y
~presented as int. It ranges from -2147483648 to (or)
2147483648. variable_name =a+ bj
sYDtax . Example: a= 3 + ij
; ·declare any variable as integer, the following syptax Here, 'a' represents a variable, 3 + ij represents a value
0
is used, of type c:omplex.
variable_name = integer value
Moreover, in Python adding an integer value to another
Example: a = 10 integer value results in a new integer value (i.e., 2 + 2
Here, 'a' represent variable,' IO' represents the value of = 4) whereas, adding an integer value to a fl.oat value
results in a new float value (i.e., 2 + 2.0 = 4.0).
type int.
Floating Point >>> 2 + 2
(rl)
Float datatype repre~ents numeric values. It is similar to 4
integer except that it lias a decimal point. In general it >>> 2 + 2.0
has 15 decimal places. Jbey are usually represented as
4.0
float.
2. String Datatypes
Syntax
To declare any variable as floating point, the following Strings ar~ the commonly used datatypes in Python. They
syntax is used, define sequence of characters declared within single or double
quotes. In :Python single quote, double quotes and three single
variable_name = floating point value
quotes ("') means the s~rµe.
Example: a= 3.14
Syntax
Here, 'a' represents variable, '3 .14' represents the value
of type float. strings are declared as follows,
(Iii) Boolean variable_name = '$tring_value'
Boolean datatype is used when a specific condition need (or)
to be tested while program execution. It consists of two variable_name = "string_value"
pos_sible values i.e., true and false. These two values can
be used for assigning the boolean values dµ-ectly. The (or)
numeric equivalent of true is 1 and false is 0. variable- name = "'strin°t,_value"'
Syntax Examples
To declare any variable as boolean, the following syntax (i) >>> 'Hello Python'
is used,
'Hello Python'
· variable_name = 'true' or 'false'
(ii) >» 'didn\'t'
Example
"didn't"
>» a= 10
>»b=l5 (iii) >>> "Author - 'Drake'"

»>a<b "Author - 'Drake'"


True (iv) >>> x = "book"
He~e, the value of variable 'a' is lesser than the value of >>> print(x)
variable 'b'' it returns true. , book.
SPECTRQM fill-IN-ONE JOORNflL FOR ENGINEERING STUDENTS
NET OF THINGS [JNTU-1- ivn
3.20
FUNDAM ENTALS OF INTER ~~~
In the above ex I .. Example ~ '~
l)NIT-3
represent a specific ' amp e (u). backslash '\' ls us~d. to Jel = ('x', 'y', 'z')
. value. Here, usually the string cot1s1sttng >:,,> tuP . •
· of single uote
is placed !·o , s \~111 be enclosed within double quotcs1 else it
I 110 smgle quotes.
They ca11 also be declared w1thout Parenth .
. • ' • ' 'z' es1s,
A string ca l . >>> tuplel = x ' Y ' ·
n ,ave more than one line. This type string . the tuple name and , ,
consist Here, tuple! is x ' 'y•, •~,
sofa backslash al the end ofU1e line h1otdcr to indicate
th t
8 1
l le s uccecding line hi its continuati on. elements. . ~,.
Dictionar y Datatypes
EJ.ample s. .
. . ry in Python IS an hunordered 8et Of
. Slring "' "Strings can have more than one line. Such D1ct10na .
t in the dictionary as a keY-vaJ Ue e1b.··1
tmgs. can be declared by using a backslash at the end of each Each elemen b
dictionary can e acces.sed throuo1. ~%
me (1.e., \n) inordcr to indicate the continuati on". elements off strings
a I f &• ~
and the va ues are o any arbj ~
print(strin g) keys are o fan datatype. tra1y ~
object or may.be O y I
String can have more than one line. Such strings can be Dictionar y is a mutable dat_atype. That is
?ec.lared by using a backslash at the end of each line inorder to . dynamic and can be modified after dect~at~. !ti
indicate the continuati on. datatype ts ·
3. List Datatype s Syntax
List is an organized /ordered series of items or values. It Dictionari es are declared as follows,
is the most flexible/ve rsatile datatype in Python. Its values are dictionary _name = {key I : value I , key2 :
defined within the square brackets where each value/item is value 2, ...... , keYn .
separated using commas. Here, all the values within a list can . .•a4
be of different datatypes. · (or)
' Syntax dictionary_name = { }
Lists are declared as follows, A dictionary can either be empty or contain ofk
- . ey.,~
list_name = [values] pairs.
(or)
Example
list_name = [] Roll_No = {"Mariya" : 21, "Seema" : 22, "Sushnu,_
A list can either be empty or it can consist of values or
items. Here, Roll_No is the dictionar y name, "Mar-
"Seema" and "Sush.ma" are keys and 21,22, 23 represer.i
Example values of their respective keys. ·
>>> x= ['book', 'pen',,250 , 45)
Q19. Discuss briefly about identifie rs and keyWrJ;
Here, the list x consists of 4 items i.e., two string values in pythok
and two integer values and the index value in list starts at O i.e.,
x[O) = 'book'. The items ofa list can be accessed ina backward / Answer. :
reverse order. This can be done by using negative index values Identifiers
i.e., to access tb,e last item of list x, x[-1] is used. This r~tums
the last value '45' from the list x. Identifiers refers to a set of valid strings that can~,
as names in a computer language. In python, the rules forna:
4. Tuple Datatype s
a identifier are as follows,
Tuples are container, that are used to store data items.
They are similar to lis~ because they store list of elements. l. The first character of identifier is either underscore . Built-in
They can have·valu es of any datatype ;md are indexed using or a character.
B
integers. They are immutabl e and they are declared using comma 2. The second character can be any alphanumeric elm These are
separated values. or underscor e. Therefor
Syntax 3. Identifiers cannot be initiated with a number orS):. members
Tuples are .declared as follows, except underscor e( _ ). the built-
tuple_nam e = (values) and ~
>>>pron
Man
4. Identifiers are case sensitive i.e., man,
(or) are not identical. variables!
tuple_ name = values Keyword s Special ,
(or)
Keyword s are reserved words which forms a coi-c
t.upJe_ name = () of the language. Use of these keywords for any other~ These~~
A tuple can either be empty or it can consist of values undersc
results syntax error. The below table depicts keywofcls~
or items, Python.

proceedings.
WARNING: Xerox/Pho tocopying of this book is a CRIMINAL act. Anyone found guilty is LIABLE to face LEGAL
3.21

----
=s.No,
i...--
1 and
Keyword
❖ _xxx
It requests private name that integrntcs within classes.

2 as ❖ nx
3 assert It s1atcs thal donot import with •frnrn module import if '•

4 break ❖ __JXX
5 class
It is a system defined name.
6 continue
def Q20. What are the rules and symbols used with re-
7
del gard to statements In Python?
8
9 elif Answer:
10 else Python statemenw need to follow rules and symbols such as,
11 except
l. Comments
12 exec
2. Module
13 finally
for 3. Newline
14
15 from 4. Colon
16 global 5. Semicolon
17 if
6. Indentation.
18 import
1. Comments
19 in
Python allows programmers to comment anywhere in
20 is
the program. Comments are provided using the hash(#)
21 lambda symbol. They are placed in the beginning of the line. The
22 not text followed by'#' symbol is ignored by the interpreter.
23 or Comments ·increases the readability of programs and
makes the programmer to understand the.logic and flow.
24 pass
25 print 2. Module
26 raise A module is a python script, it exists physically on
27 return the disk in the form of files. A portion of module that
try
becomes very lengthy can be shifted to another module.
28
29 while 3. Newline
30 with Newline breaks a single python statement into multiple
31 none lines. The backsla~h symbol ('\') is used to denote a
32 yield newline.
Example
Table: Keywords
if(student_age > 17) and\
Built-in
(studenLGPA> 3.5):
Built-ins are special names identifiers used by interpreter.
These are not keywords but considered as reserved for system. admission = I
Therefore, programmers should not use them: Built-ins are However, lines can be continued on next line without
members of built-in module. Interpreter automatically imports using '\' in two exceptions.
~ built-in module before the program begins ot user enter the
❖ One when enclosing operators are used, such as
>>~ prompt in the interpreter. They can also be used as global
square brackets or parenthesis.
variables that can be accessed anywhere in programs.
❖ Another when triple quotes are used for strings.
Special Underscore Identifiers
Example
'IL In Python, ,special underscore variables are also used.
•u,;se Variab (i) "'SIA edu group pioneer in ..... today"'
~ . !es are both prefixed and suffixed. Some of these
re identifiers are as follows (ii) SIA need (240, more .... )
'
SPECTRON flLL·IN-ONE JOORNflL FOR ENGINEERING STUDENn
rT
' I
3.22
4. Colon
FUNDAMENTALS OF INTERNET OF THINGS [JNTU-HYoeRA,~

~
l ❖
'
. kn
In python, a set of individual s1ntomcnts th~t forms a siuglc code block are own as sm es .
C t --
" . 't ,,

L , l need a suite and a header line.


❖ omp ex or com.pound statc111c11ts such ns (if, while, lief and class) t.ia
Al •d, •t· . d th fi Jlowed by one or more lines.
lC,l ct ltlc stnrts with a keyword nncl ends with colon( :) an ° .
en
S. Sl'nticolon
.Multiple statements are allowed iJ1 a single line using semicolon (;). However, they can be used only when none of
statements initiate a new code block. ~
Example

.
import abc; p = ' Today'·
'
6. Indentation
, .
In python, indentation is used to delimit blocks of code. All lines of a program mu~t be indented th e same number of sp
i.e., it needs exact indentation. Indentation is applied with spaces or tab. However, sp~ces are preferred.

3.2 INTR~DUC_T ION TO RASPBERRY Pi, INTERFACING RASPBE_RRY Pi WITH BA.s1


PERIPHERALS
Q21. Give a brief introduction to Raspberry Pi. List out the peripherals of Raspberry Pi.
Model Paper-I,
Answer:

Raspberry Pi is a ·device th.at comes in the size of equal to credit/debit card works like a mini computer and has
capability of performing tasks of a desktop corhp~ter. It is a lo~ cost device which can run on different yersions of Lin,
I~ connects sensors and actuators with the help of VO pins. A Raspberry Pi board shown beiow is inc.orporated with seve
compone_nts/periph_erals.
Audio
GPIO Pins RCA Video Jack

LED Status

USB Controller
DSI (Display
Connector)
( '• USB 2.0

· SD Card Slot

Ethernet
Micro-USB
HDMI CSI (Camera
Connector)

Figure: Components of Raspberry Pi


The major components or peripherals among the above components are discussed below
. '
1. Power Input
The power input to Raspberry Pi is provided through a ,micro USB connector.

. 2. VSB Ports
There are two ~SB ports on _Raspberry Pi that can provide power upto 100mA. However, an external power hub is-need
to connect devices that reqmre more power. . .

WARNING: xerox/Photocopying of this book is a CRIMINAL act. Anyone found guilty is LIABLE to face LEGAL proceed'mgs.
3
~~,1- ~---
- ---- ---- ---- ---- -;-- :--- -:-~ ---- ---- ~·p :.:_ 19
3. '8
~ r n e t Po•·t-s :t Areh
·), rncre is RJ45 Ethe111et porl on hoard which is ttRcd to ll i.ii a type of Arch I.lnux port dcvcl<>ped for AMf)
dcvicc11. ,
cml)lcd to1lntcmel.
4. lUSC OS
processor and RAM
II fl comprcR'lcd form of operatin~ sy3tem with gr>od
fhC processor of Raspberry Pi is ARM where
speed.
ARMI 17672-F can support 700 Ml lz power. The RAM
__ A f(lr tllis processor is about 5I 2 MB.
5. Pldorn
l)Sl,,V
lt is a type of Fedora Linux particularly developed for
GPIO Pins Raspberry Pi.
there are four types of general purpose input/output
6. OpenELEC
jns on Raspberry board such as SPl interface pins, true
~PIO pins, RX: and TX pins and 120 interface pins. 1t is XBMC based media-center distribution which is
used friendly and offers good speed.
OSI (Display Serial Interface)
Raspberry Pl Interfaces
It is used as an interface between LCD panel and
There are three types of Raspberry Pi interfaces that
Raspberry Pi. support data transfer. They are J2C, Serial and SPI.
CSI (Camera Serial Interface) 1. 12C
It is used as an in~erface between camera and Raspberry 12C interface is used to provide interconnection between
hardware modules using SDA (data line) and SCL (clock
Pi.
line) pins. Using·these pins, it supports synchronous data
8. , SD Carft Slot ,
transfer.
It is used to insert an external SD card containing Linux
2. · Serial
unage.
The serial interface allows data transfer among serial
9• BDMI Output peripherals using receive (Rx) and transmit (Tx) pins.
It is used to provide Audio and video from Raspberry 3. SPI (Serial Peripheral Interface)
Pi. SPI is a type of serial data protocol that offers
10. Audio/Video Output synchronous ·data transfer among peripheral devices
using the following five pins.
It is used to obtain audio/video output from Raspberry
Pi to televisions. (a) Chip Enable (CEO)
The CEO pin is used to enable and disable the
Q22. What are the various flavors/versions of Linux
supported by Raspberry Pi? List out the devices.
interfaces of Raspberry Pi. (b) Chip Enable 1 (CEl)

Answer: This pin works similar to CEO ..

FlavorsNersions of Raspberry Pi (c) MISO (Master In Slave Out)


MISO is a master pin that is used to forward data
The different flavours/versions of Linux supported by
to peripherals.
Raspberry Pi are as follows,
1. (d) SCK (Serial Clock)
Raspbian
SCK is a clock tpat s_upports synchronization of
ltis a Linux based Debian Wheezy port that is particularly
data transmission.
used for Raspberry Pi.
(e) MOSI (Master Out Slave In)
2. RaspBMC
MOSI is slave pin that is used to forward data to
It is a type ofXBMC m~dia-center distribution. the master i.e., MISO.

SPECTRUM fill-IN-ONE JOURNAL FOR ENGINEERING STUDENfl


e~
3 .2 4 TE R N E T OF TH INGS {J N TU-HYo ~8
FUND AMENTALS O F IN
.
Q23. Li st a d aspbe;.... , Pf
. · n &Xplafn the R ··Y oO'llmand• .
A lls W er :
• J

.
e fre qu ently t1s ed R ds ar e tabulated below,
So me of th · as pb cny Pi com m an

Connnand Function

mv or re na m e flJe.
lt is us ed to m ~v e
cd di re ct or y.
Jt is us ed to chattgc
It . re at e ar ch iv e.
ta r is us ed to ex tra ct /c
m disk sp ac e.
e us ag e of.file sy ste
df It is us ed to re po rt th th pa tte rn .
gr ep pr in t th e lin es wh ic h ar e m at ch in g wi
It is us ed to
ca t It is us ed to displa
y th e file contents.
e th e file.
nu It is Used to re m ov
cr ea te a directory.
m kd ir lt is us ed to m ak e or
folders an d fifes.
Js It is us ed to list the e directory.
pw d is us ed to pr in t na m e of cu rre nt ly activ
It s.
ls us b It is us ed to displa
y all the USB device
.
re ne tw or k interface
ifc on fig It is us ed to con.figu ader.
iv e ne tw or k downlo les.
w ge t It is a no n- in t~ ra ct
tio ns , in te rfa ce sta tistics an d ro ut in g tab
y ne tw or k connec
.p et sta t It is us ed to pr in t th1
wn th e device.
sh ut do w n It is us ed to sh ut do
device.
re bo ot It is us ed to re bo ot
r a file.
lo ca te It is us ed to se ar ch fo

~RY I
!:. ~~=~::.::::;~o~ ;:::P:::::::::::! .
It allow s an y python program that
Pi .

can be execute
.
Model Paper~,. j
A ns w er : ementat io n. es. It utilizl
d python for its impl tuators and its interfac
pp or t bo th Li nu x an types of se ns or s an d ac further J
Ra sp be rr y Pi c~n su it us es GP IO pi ns along wi th various m se ns or s ca n be processed tasks of
su pp or t th is, taine d fro ng Rasp '
on an y m ac hi ne . To to m ak e it us ef ul for IOT. The input ob in g an em ail etc. Consider the followi
GP IO pi ns nd
the capabilities of µ-ansferring data, se
ca n be pe rfo rm ed on the input such as
di ffe re nt ac tio ns
Pi _us in g py th on .
5, Q26.
er re fe r Unit-III, Q2
Fo r re m ai ni ng an sw
spberry Pi.
s ho w LE D is co nt ro lle d with Ra
Q 25 . Di sc us
,
A ns w er : n in the figure below
te d to th e Ra sp be rry P'i board as show
Th e LE D is co nn ec
•• k.-t
•• -e .t .t •• ' " "' ·
., . lit t ·► 1
~":t t- ·· :,'""~ ·· ,·:
·• ·: , . <i ••,,, ,
1
J'" ~ ll > .. 't 11 * 1< ·•...-..
. . . . · ••11:••
• I • • • t.
I f t I♦ f "I . • • f" 4 I ..
• \- ..-, , ••• ' ,. .
<t' t ·fli\ . , •• , ; ► 'Y. ,..' '
••• f' 1'" • • ' .
<I t•" •• •• •
,." • t • • , ,I I.. .. .... .... . .
. , ~
- · ... " ~ ••• t 't ....
f'

,,,· ~11(• 4;; _••· · .. .... . '. .. . ..


II O f,. ~ . • ·.• 0
1,
o, <i ,._.

"'" :A, )'\ • •• • • • •

······~•--•·~ t., ,·•. .'l•....··. .,••. ..1.t...•1•.....~ .......... ., .••,


'
••"••" '"'1 tr1 '••• •• • • • • • , .
, •T'>f~ • ,. .. , • 4 • 4 • .. • •
,
; -, -) t , r ... • , - ,,,
. . . . . . .. .. ,
. .. ., t ~ · . .. ,_,~ ~ ' " •~
• ., ,. ., , t t . . . . .. . . ...

.... ,, ... . . . ..••. ,i..,., ,,• . . ......,.......


. .. f .. . . · · ~
··
~ -~

D with Raspberry Pi
Figure: Controlling LE
proceedings.
E to face LE GA L
act. An yo ne fou nd guilty is LIABL
AL
s book is a CRIMIN
Ph 0 t0 CO
pying of thi
ING: xe ro x!
3.25
. f,3
~ e LED can be switched ontoff from Raspberry ~i . The python code to control LED based rm light sensed
fh . console in the fullowmg way, . using LDR is an follow'!,
,ndhne .
~~((f. $ t:cho 18 > /sys/clnss/gpio/export import RPi <JPJO as <,PIO
$ cd/sys/dass /gpio/gpio l 8
itnp 11 rt tim•;
$ echo out > dirccti0n
OPfO.sctmode (OPl fJ.BCM )
$ echo l ;;, value # Switching LED on
klr_ thr - I000
$ echo O> value # Switching LED off
LDR_PI N = 18
'fhecodcto make LED l~onnectcd to Raspberry Pi) blink
second using p)1bon ts as follows, LIGHT _PIN - 25
•._e,-erf
fi iroport RPi.GPlO as GPIO defi ne readLOR(P fN ):
imPort time read o: 0
GPIO.setmode (GPIO.BCM) GPIO.setup(LJGHT_pIN, GPJ.OUT)
GPIO.setup (18, GPIO.OUT) GPIO.output(PIN, false)
while Tore: time.sleep (0. l)
GPIO, output (18, True)
GPIO.setup(PIN, GPIO.IN)
time.sleep( 1)
while. (GPIO.input{PIN) ==False):
GPIO.output (18, false)
read = read + l
time.sleep ( 1)
return read
The above code makes use of RPi and GPIO for

::d
ai.
lling the GPIO. The pin 18 is set to generate output with
false values that switch after every second.
def switchOnLight (PIN):
GPIO.setup(PIN, GPIO.OU1)
1
Explain about interfacing light sensor with GPIO.output(PIN, True)
Raspberry Pi. .
def switchOflLight (PIN):
Model Paper-Ill, Q6(b)
AD5Wd:
GPIO.se!tlp(PIN, GPIO.OUT)
A Light Dependent Resistor (LDR) which is a light
sensor can be interfaced with Raspberry Pi by connecting one GPIO.Output (PIN, False)
end to 3.3v and other end to lµF capacitor and GPIO pin. A
while True:
part from this an LED is also connected to pin 18 so that if can
be turned on/off based on the light sensed. ldr- Read= readLDR (LDR PIN)
-
., " • •.•• ,... ~ ~.••.• • P·•
j . ~ , ♦- • t .~ •'C~~•~ • •··· • -i if ldr_read < ldr_thr:
:1 • '" ' 4 i- • • • ]: .<"t • t t~ ft •.-..
- - · •
1 • •
/, .. •
l ,• '
,, •

t"~ • '\~· •••• ,4♦ ~~ l) ••
'

'- • ~ ~- ..
• ' .....

-~;~ t.' .. ••~


t '
.. .._. switchOnLight (LIGHT_PIN)
·, : . :_ ... • , • It • . ,•. , •., 1~·
'-:t •••• , .. .. .. .!
:I .. ..... <.::: ;;:
i•• • •• (' \.. ' .. ) t.
else:

.: ,••·., •••t•
; .. .

:1
··•'•
......

, • • ~ ,,
t, • ,: ••·
;Ii' ♦ ••
~ •• , ••

;,r, • • ~•
t~
switchOflLight (LIGHT_PIN)
, • ·•
•• c:•••• J '' •••
, . . . . . a; • . ,. • ,.
time.sleep( 1)
,,.
~ ,••-•ifl)i'' . • ,.
In the above code, readLDR( ) function is used for
il .. :::::,.-: :::: 1· .
i,•• -···· •••.•••• returning a count proportional to light level. It carries LDR pin
;J ... , , .......... •t>

;1•· ...\'... ... . which is set to output and low followed by input respectively.

,:........
':::,:'~···... l:.:
. ... ,. . .
... ;-~·
! '· •••. , ....... . The inpqt will read high until capacitor gets charged via resistor.
When the read value of input triggers high, the counter is

i
=: : : ,
• '. • •
., . f: t •••
stopped .
••• , . *~ *•"·· ••
•• ,.;,~ •·· ... . ... ,
••
•• •••••
, I! . . . . . . . .

Figure: Interfacing LOR with Raspberr~ Pi

SPECTROM flLL-IN-ONE JOORNflL FOR ENGINEERING STODENTS

You might also like