LAB MANUAL
ON
APPLIED PYTHON PROGRAMMING
DEPARTMENT OF ELECTRICAL AND ELECTRONICS
ENGINEERING
KODADA INSTITUTE OF TECHNOLOGY & SCIENCE FOR
WOMEN
NEAR RANGANI GUDI, KODADA,SURYAPET(DT),TELANGANA-508206
Department of Computer Science and Engineering
Downloaded by Sreelakshmi Nelluri
VISION AND MISSION OF CSE DEPARTMENT
Vision
To acknowledge quality education and instill high patterns of discipline making the
students technologically superior and ethically strong which involves the improvement in the
quality of life in human race.
Mission
To achieve and impart holistic technical education using the best of infrastructure,
outstanding technical and teaching expertise to establish the students in to competent and
confident engineers.
Evolving the center of excellence through creative and innovative teaching learning
practices for promoting academic achievement to produce internationally accepted
competitive and world class professionals.
Program Educational Objectives:(PEO’s)
PEO1: Graduates of program will have complete command over all key principles of hardware and
software areas.
PEO2: Graduates of program will develop skills to identify a real life situation, analyze the
problem,formulate a solution and help industry and individuals overcome issues.
PEO3: Graduates of program will cultivate professional skills, develop soft skills and be ready with
complete skill set demanded by industry or higher learning centers.
Program Specific Outcomes(PSO’s):
PSO-1: Computing Techniques: Apply the knowledge about principle of programming
languages,computer algorithms, databases, system software and computer network for the
interconnection.
PSO-2: Computer product and Application Development: Interpret and analyze the problem, formulate
an efficient hardware and software solution for the real world. Socio - industry related problems and
needs using computing methodologies and latest technologies.
PSO-3: Successful Career and Entrepreneurship Perspectives: Fulfilling desire by attaining
employment, excel in competitive examinations, higher studies, research and initiate startup’s.
Program Outcomes (POs):
Downloaded by Sreelakshmi Nelluri
1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering fundamentals,
and an engineering specialization to the solution of complex engineering problems.
2. Problem analysis: Identify, formulate review research literature and analyze complex engineering
problems reaching substantiated conclusions using first principle of mathematics, natural science and
engineering science.
3. Design/development of solutions: Design solutions for complex engineering problems
and design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.
4. Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and
synthesis of the information to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering
activities with an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and
need for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and
write effective reports and design documentation, make effective presentations, and give
and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the engineering
and management principles and apply these to one's own work, as a member and leader in a
team, to manage projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
Downloaded by Sreelakshmi Nelluri
KODAD INSISTUTE OF TECHNOLOGY AND SCIENCE FOR WOMEN
SYLLABUS
CYCLES PROGRAMS
1. DownloadingandInstallingPythonand Modules
a) Python3on Linux
FollowtheinstructionsgivenintheURL[Link]
install3/linux/
b) Python3on Windows
Follow the instructions given in the URL
[Link] Windows
installation of Python is harder!)
c) pip3onWindows andLinux
Install the Python package installer by following the
instructions given in the URL
[Link]
install-and-use-pip3/
d) Installing numpyandscipy
Youcaninstallanypython3packageusingthecommandpip3 install
<packagename>
e) Installing jupyterlab
Install frompipusingthecommandpipinstalljupyterlab
Page 4
KODAD INSISTUTE OF TECHNOLOGY AND SCIENCE FOR WOMEN
2. IntroductiontoPython3
a) Printingyour biodataonthescreen
b) Printingalltheprimeslessthanagivennumber
c) Finding all the factors of a number and show whether it is a perfect number,
i.e., thesumofallitsfactors(excludingthenumberitself) isequaltothenumberitself
CYCLE-1
3. Defining andUsingFunctions
a) Writea functiontoread data fromafile anddisplayitonthe screen
b) Defineabooleanfunction ispalindrome(<input>)
c) Writeafunctioncollatz(x) whichdoesthefollowing:ifx isodd,x=3x+1; if x
is even, then x=x/2. Return the number of steps it takes for x= 1
d) WriteafunctionN(m,s)=exp(-(x-m)2/(2s2))/sqrt(2π)s thatcomputes
the Normal distribution
4. Thepackagenumpy
a) Creatingamatrixofgivenorder mxn containingrandomnumbers inthe
range 1 to 99999
b) Writea program that adds, subtractsand multiplies two matrices. Provide
an
interfacesuchthat,basedontheprompt,thefunction(addition,subtraction,
multiplication) should be performed
c) Writeaprogramtosolve asystemofnlinear equationsinnvariables using
matrixinverse
5. Thepackage scipyandpyplot
a) Findingiftwosetsofdatahavethesamemeanvalue
b) Plottingdataread from a file
c) Fitting afunctionthrough asetadata pointsusingpolyfitfunction
d) Plottingahistogramof agivendataset
7. InstallingOSonRaspberryPi
a) InstallationusingPiImager
b)Installationusingimagefile
DownloadinganImage
WritingtheimagetoanSDcard
6. Thestrings package using
CYCLE-2 a)Linux
Readtextfroma fileand printthenumberof lines,wordsandcharacters
b)usingWindows
Read textfromafileandreturn alistofallnletter words beginningwitha vowel
Booting up
c) Findingasecretmessagehiddenina paragraphof text
d) Plotahistogramofwords accordingtotheirlengthfromtext read from afile
8. AccessingGPIOpinsusing Python
a) Installing GPIO Zero library.
First,updateyourrepositorieslist:
sudo apt update
TheninstallthepackageforPython3: sudo
apt install python3-gpiozero
Page 5
KODAD INSISTUTE OF TECHNOLOGY AND SCIENCE FOR WOMEN
9.b)BlinkinganLEDconnectedtooneoftheGPIOpin c)Adjusting the
brightness of an LED
d)AdjustthebrightnessofanLED(0to100,where100meansmaximumbrightness)usingthein- built
PWM wavelength
[Link] Data
DHTSensorinterface
ConnecttheterminalsofDHTGPIOpinsofRaspberryPi.
Import the DHT library using import Adafruit_DHTRead
sensor data and display it on screen.
Page 6
KODAD INSISTUTE OF TECHNOLOGY AND SCIENCE FOR WOMEN
Page 7
KODAD INSISTUTE OF TECHNOLOGY AND SCIENCE FOR WOMEN
LABCYCLE-1
DownloadingandInstallingPythonand Modules
1a)Python3onLinux
$python3–version
$sudoapt-get update
$sudoapt-getinstall python3.6
1b)Python 3on Windows
Installationsteps:
FourPython3.10installersareavailablefordownload-twoeachforthe32-bitand64-bitversions of
theinterpreter. The web installer is asmall initial download, and it will automatically download the
required components as necessary.
Ifyouselect“InstallNow”:
• Youwill notneedtobeanadministrator (unlessasystemupdatefortheCRuntimeLibraryisrequiredor you
install the Python Launcher for Windowsfor all users)
• Pythonwillbeinstalledintoyouruser directory
• ThePythonLauncherforWindowswillbeinstalledaccordingtotheoptionatthebottomofthefirstpage
• Thestandardlibrary,testsuite,launcherandpipwillbeinstalled
• Ifselected,theinstalldirectorywillbeaddedtoyour PATH
• Shortcutswillonlybevisibleforthecurrent user
DCollegeofEngineeringforWomen
1c)pip3onWindowsandLinux
FirstCheckwhichversionofpip3isinstalledbyentering: pip3 --
version
Outputshouldbesimilarto:
pip20.0.2fromC:\Python38\lib\site-packages\pip(python3.8)
ConfirmwhichversionofPython(ifany)isinstalledonyourcomputerbyentering: python
--version
Outputshouldbesimilarto:
Python 3.8.2
Pip3Installation
Python3.4+inmostoperatingsystemsincludespip3bydefault.Ifyourpythonversionislessthan3.4,thenyou should
upgrade your Python version which will automatically install pip3.
Pip3 Upgrade
InoperatingsystemenvironmentsthatalreadyhavePython3andpip3installations,youcanupgradepip3,by entering:
Page 8
KODAD INSISTUTE OF TECHNOLOGY AND SCIENCE FOR WOMEN
python-mpip3install--upgradepip Pip3
Usage
ToinstallaPythonpackage,enter:
Pip3install<package_name>
Installpip3UbuntuandDebianLinux
Ubuntu18.04hasbothPython2andPython3installedbydefault,andhencehastwopipvariantsforeachPython version.‘pip’,
refers to Python 2. pip3 refers to Python 3.
EnterthefollowingcommandtoupdateLinux:
sudo apt update
Enterthefollowingcommandtoinstallpip3: sudo
apt install python3-pip
Theabovecommandwillalsoinstallallpip3 dependencies.
Installpip3Windows
Toinstallorupgradepip3inaWindowsenvironmentthatalreadyhasPython3installed: Download
the latest version of [Link] from
<[Link]
You can also use the curl command to download [Link]:
curl[Link]
[Link],andenterthefollowingcommandtoinstallpip3andits dependencies:
[Link]
Youcanverifythatpip3isinstalledbynavigatingtothedefaultpip3installationdirectory,eg.C:\python38\scripts\, and enter:
pip3–version
1d)Installing numpyand scipy
ToinstallNumPywiththe packagemanagerforPython3,run:
pip3installnumpy
ToinstallSciPywiththepackagemanagerforPython3,run:
pip3installscipy
1e)Installingjupyterlab
[Link]'sdesignatedpackagemanager,pip,makesiteasyto install
JupyterLab. Begin with dnf:
$sudodnfupdate
$sudodnfinstallepel-release
$sudodnfinstallpython3
$sudodnfinstallpython3-pip
Afterinstallation,verifythatPythonandpipareaccessible:
$python3–version
Page 9
KODAD INSISTUTE OF TECHNOLOGY AND SCIENCE FOR WOMEN
$python3-mpipinstall--user--upgradepip
$python3-mpipinstall--userjupyterlab
[Link]
2a)Printing yourbiodataonthe screen
print(name)
print(age)
print(course)
print(address)
2b)Printingalltheprimeslessthanagivennumber #
First, we will take the input:
n=int(input("Please,EntertheUpperRangeValue:"))
print("ThePrimeNumbersintherangeare:") for
number in range (2, n):
if number>1:
foriinrange(2, number):
if (number%i)==0:
break
else:
Page 10
KODAD INSISTUTE OF TECHNOLOGY AND SCIENCE FOR WOMEN
print (number)
2C)Findingallthefactorsofanumberandshowwhetheritisaperfectnumber,i.e.,thesumof all its
factors (excluding the number itself) is equal to the number itself
num=int(input("Enterthenumber:"))
sum_v=0.
foriin range(1,num):
if(num%i==0):
sum_v=sum_v+i.
if(sum_v==num):
print("Theenterednumberisaperfectnumber")
else:
print(“Numbernotperfectnumber”)
DefiningandUsingFunctions
3a)Write afunctiontoreaddata fromafile anddisplayit onthe screen
file1=open("[Link]","w")
L=["ThisisDelhi\n","ThisisParis\n","This isLondon\n"]
#\nisplacedtoindicateEOL(EndofLine)
[Link]("Hello \n")
[Link](L)
[Link]()#tochangefileaccessmodes
file1=open("[Link]","r+")
print("OutputofReadfunctionis") print([Link]())
print()
#seek(n)takesthefilehandletothenth #
bite from the beginning.
[Link](0)
print("OutputofReadlinefunctionis")
print([Link]())
print()
[Link](0)
#Toshowdifferencebetweenreadandreadline
print("Output of Read(9) function is ")
print([Link](9))
print()
[Link](0)
print("OutputofReadline(9)functionis")
print([Link](9))
[Link](0)
#readlines function
print("OutputofReadlinesfunctionis")
print([Link]())
print()
Page18
Page 11
KODAD INSISTUTE OF TECHNOLOGY AND SCIENCE FOR WOMEN
[Link]()
3b)Defineabooleanfunctionispalindrome(<input>)
def isPanlindrome(num):
returnint(num!=0)and((num%10)*\
(10**int([Link](num,10)))+\
rev(num// 10))
#Readingnumber
test_number=input(“Enteranynumber”)
#printingtheoriginalnumber
print("The originalnumber is:"+str(test_number))
#[Link]()+recursion+listcomprehension #
for checking a number is palindrome
res=test_number== isPalindrome(test_number)
#printing result
print("Isthe numberpalindrome?:"+str(res))
3c)Writeafunctioncollatz(x)whichdoesthefollowing:ifxisodd,x=3x+1;ifxiseven, then x = x/2.
Return the number of steps it takes for x = 1
def printCollatz(n):
#Wesimplyfollowsteps
#while wedonot reach1
Count = 0
whilen!=1:
#Ifnisodd if
n & 1:
n=3*n+1
count++
#Ifeven
else:
n=n //2
count++
#Print1attheend print(count)
# Driver code
printCollatz(6)
d)WriteafunctionN(m,s)=exp(-(x-m)2/(2s2))/sqrt(2π)sthatcomputestheNormaldistribution
import math
defsolve(x,m):
s= 1
result=[Link](-((x-m)**2)/2*(s**s))/((2*[Link]*s)**0.5) return
result
Page 12
KODAD INSISTUTE OF TECHNOLOGY AND SCIENCE FOR WOMEN
print(solve(4,2))
4a)Creatingamatrix ofgivenordermxncontainingrandomnumbersintherange1to99999 import numpy
as np
#1stargument-->numbersrangingfrom0to9, #
2nd argument, row = 2, col = 3
Example1
array=[Link](10,size=(2,3))
print(array)
Example2
array=[Link](99999,size=(10,5)) print(array)
4b)Writeaprogramthatadds,[Link],based on the
prompt, the function (addition, subtraction, multiplication) should be performed
METHOD1
#inputtwomatricesofsizenxm
matrix1 = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
matrix2=[[5,8,1],
[6,7,3],
[4,5,9]]
res=[[0for xinrange(3)]for yinrange(3)]
#explicit forloops
foriin range(len(matrix1)):
forjinrange(len(matrix2[0])):
fork in range(len(matrix2)):
#resultedmatrix
res[i][j]+=matrix1[i][k]* matrix2[k][j]
print (res)
METHOD2
#Weneedinstallnumpyinordertoimportit
import numpy as np
#inputtwomatrices
mat1 =([1,6, 5],[3 ,4,8],[2, 12, 3])
mat2 =([3,4, 6],[5,6, 7],[6,56, 7])
#Thiswillreturndotproduct
res = [Link](mat1,mat2)
#printresultedmatrix
print(res)
Page 13
KODAD INSISTUTE OF TECHNOLOGY AND SCIENCE FOR WOMEN
4c)Writeaprogramtosolveasystemofnlinearequations innvariablesusingmatrix inverse SystemsofLinear
Equations
[Link] below:
8x+3y−2z=98x+3y−2z=9
−4x+7y+5z=15−4x+7y+5z=15
3x+4y−12z=353x+4y−12z=35NumPy'[Link]()functioncanbeusedtosolvethissystemof
equations for the variables xx, yy and zz.
[Link]()arebelow: Create
NumPy array A as a 3 by 3 array of the coefficients
Create a NumPy array b as the right-hand side of the equations
Solvefor the values of xx, yy and zzusing [Link](A, b).
[Link]. In [1]:
importnumpyasnp
A= [Link]([[8,3,-2], [-4, 7,5], [3, 4, -12]])
b=[Link]([9, 15,35])
x=[Link](A,b) x
Out[1]:
array([-0.58226371,3.22870478, -1.98599767])
Wecan plugthe valuseofxx,yyandzzbackinto oneofthe equationstocheck the answer.
xxisthefirstentryofthearray,yyisthesecondentryofthearray,and zzisthethirdentryofthearray. xx = x[0]
yy =x[1]
zz= x[2]
Whenthesevaluesarepluggedintotheequationfromabove:
8x+3y−2z=98x+3y−2z=9
Theanswershouldbe9.0. In
[2]:
8*x[0]+3*x[1]-2*x[2]
Out[2]:
9.0
5a)Findingiftwosetsofdatahavethesamemeanvalue #
Importing the statistics module
fromstatisticsimportmean
#Importingfractionsmoduleasfr #
Enables to calculate mean of a
#setin Fraction
fromfractionsimportFractionasfr
#tupleofpositiveintegernumbers data1
= (11, 3, 4, 5, 7, 9, 2)
#tupleofanegativesetofintegers data2 =
(-1, -2, -4, -7, -12, -19)
#tupleofmixedrangeofnumbers data3 =
(-1, -13, -6, 4, 5, 19, 9)
#tuple ofasetoffractionalnumbers
data4 =(fr(1, 2),fr(44, 12), fr(10,3), fr(2, 3))
#dictionary ofaset ofvalues
Page 14
KODAD INSISTUTE OF TECHNOLOGY AND SCIENCE FOR WOMEN
#Onlythekeysaretakenin #
consideration by mean()
data5={1:"one",2:"two", 3:"three"}
#Printing themeanofabove datasets
print("Meanofdataset1is%s"%(mean(data1)))
print("Meanofdataset2is%s"%(mean(data2)))
print("Meanofdataset3is%s"%(mean(data3)))
print("Meanofdataset4is%s"%(mean(data4)))
print("Meanofdataset5is%s"%(mean(data5)))
Output:
Meanofdataset1is5.857142857142857 Mean
of data set 2 is -7.5
Meanofdataset3is2.4285714285714284
Mean of data set 4 is 49/24
Meanofdataset5is2
5b)Plotting data readfrom afile
Requirement:
Atextfile fromwheredata [Link]=[Link]
[Link] import
csv
X= []
Y= []
withopen('[Link]','r')asdatafile:
plotting=[Link](datafile,delimiter=',')
for ROWS in plotting:
[Link](int(ROWS[0]))
[Link](int(ROWS[1]))
[Link](X, Y)
[Link]('LineGraphusing CSV')
Page 15
KODAD INSISTUTE OF TECHNOLOGY AND SCIENCE FOR WOMEN
[Link]('X')
[Link]('Y')
[Link]()
Output:
[Link]
import numpy as np
X,Y=[Link]('[Link]',delimiter=',',unpack=True)
[Link](X,Y)
[Link]('LineGraphusingNUMPY')
[Link]('X')
[Link]('Y')
[Link]()
Output:
Page 16
KODAD INSISTUTE OF TECHNOLOGY AND SCIENCE FOR WOMEN
5c)Fittingafunctionthrough asetadata points using polyfit function
EXAMPLE-1
importnumpyasnp
[Link]
[Link](12)
x=[Link](0,1,25)
y=[Link](x)+0.3*[Link](25) p
= np.poly1d( [Link](x, y, 4) )
t = [Link](0, 1, 250)
[Link](x,y,'o',t,p(t),'-')
[Link]()
EXAMPLE-2
importnumpyasnp
[Link]
[Link](12)
x=[Link](-20,20,10)
y=2*x+5
coeff=[Link](x,y,2)
xn=[Link](-20,20,100)
yn = np.poly1d(coeff)
[Link]( xn,yn(xn),x,y,'o')
5d)Plotting ahistogramofagiven data set
ToplotahistogramusingMatplotlib,wecanfollowthestepsgivenbelow− Make a
list of numbers and assign it to a variable x.
[Link]()methodtoplotahistogram.
Compute and draw the histogram of *x*.
Wecanpassn-Dimensionalarraysinthehistargumentalso. To
show the plotted figure, use the [Link]() method.
Example
frommatplotlibimportpyplotasplt
x =[300, 400, 500, 2000, 10]
[Link](x,10)
[Link]()
Output
Page 17
KODAD INSISTUTE OF TECHNOLOGY AND SCIENCE FOR WOMEN
6a)Readtextfromafileandprintthenumberoflines,wordsandcharacters
METHOD-1
Thisversionoftheprogramcountsthenumberoflines,wordsandcharacters(includingspaces)using string
methods.
Solution algorithm:
[Link] body of the
cycle:
Thecounteroflines isincrementedby1.
Thestringissplitintowordsusingthe [Link] of words.
This number is added to the word counter.
To ignore the newline character ('\n'), we remove it using the strip method. The length of the remaining
stringincharactersismeasuredbythe [Link].
Thetext file:
onetwothree city
town
bigsmall
Codeoftheprogram:
file= open('[Link]')
lines=0
words=0
symbols=0
forlineinfile:
lines += 1
words += len([Link]())
symbols+=len([Link]('\n'))
print("Lines:", lines)
print("Words:", words)
print("Symbols:",symbols)
Result:
Lines:3
Words:7
Symbols:31
Page 18
KODAD INSISTUTE OF TECHNOLOGY AND SCIENCE FOR WOMEN
METHOD-2 DCollegeofEngineeringforWomen
Thisisamoreclassicalalgorithm [Link] lenfunctionandstring methods.
[Link],whencountingcharacters,notonlythe newline
character is not taken into account, spaces and tabs are also excluded.
To count the number of words, an additional variable (pos) is introduced, which "shows" whether we are
[Link]-whitespacecharacter isencounteredandbeforethatwewereoutsidethe word,
then a new word has begun. The word counter should be incremented by 1.
Thetext file:
onetwothree city
town
bigsmall
Codeoftheprogram:
file= open('[Link]')
lines=0
words=0
letters=0
forlineinfile:
lines += 1
forsymbol inline:
ifsymbolnotin('','\n','\t'): letters
+= 1
pos='out'
forsymbol inline:
ifsymbol!=''andpos=='out':
words += 1
pos='in'
elifsymbol=='':
pos = 'out'
print("Lines:", lines)
print("Words:",words)
print("Letters:",letters)
Result:
Lines:3
Words:7
Letters: 27
6b)
Readtextfrom afile andreturn alistofall nletterwordsbeginning witha vowel
METHOD-1
#initializing list
test_list=["all","love","and","get","educated","by","gfg"]
#printingoriginallist
print("Theoriginal list is:"+str(test_list))
res=[]
vow="aeiou"
forsubintest_list: flag
= False
Page 19
KODAD INSISTUTE OF TECHNOLOGY AND SCIENCE FOR WOMEN
#checkingforbeginchar for
ele in vow:
[Link](ele):
flag = True
break
if flag:
[Link](sub)
#printing result
print("Theextractedwords:"+ str(res))
METHOD-2
Usingany(),startswith()andloop
#initializing list
test_list=["all","love","and","get","educated","by","gfg"]
#printingoriginallist
print("Theoriginal list is:"+str(test_list))
res=[]
vow="aeiou"
forsubin test_list:
#checkforvowelbeginning
flag=any([Link](ele)foreleinvow)
ifflag:
[Link](sub)
#printing result
print("Theextractedwords:"+ str(res))
METHOD-3
Usingfind()method
#Startingwithvowels #
initializing list
test_list=["all","love","and","get","educated","by","gfg"]
#printingoriginallist
print("Theoriginallistis:"+str(test_list)) def
vowelstart(s):
if([Link]("a")==[Link]("e")==[Link]("i")==[Link]("e")==[Link]("u")==0): return
True
returnFalse
res = []
for sub in test_list:
if(vowelstart(sub)):
[Link](sub)
# printing result
print("Theextractedwords:"+ str(res))
Page 20
KODAD INSISTUTE OF TECHNOLOGY AND SCIENCE FOR WOMEN
DCollegeofEngineeringforWomen
Page 21
KODAD INSISTUTE OF TECHNOLOGY AND SCIENCE FOR WOMEN
6c))Findingasecretmessagehiddeninaparagraphoftext #
Taking input from user
data='Welcometo...'
# conversion Chart
conversion_code={
#UppercaseAlphabets
'A':'Z','B':'Y','C':'X','D':'W','E':'V','F':'U',
'G':'T','H':'S','I':'R','J':'Q','K':'P','L':'O',
'M':'N','N':'M','O':'L','P':'K','Q':'J','R':'I',
'S':'H','T':'G','U':'F','V':'E','W':'D','X':'C', 'Y':
'B', 'Z': 'A',
#LowercaseAlphabets
'a':'z','b':'y','c':'x','d':'w','e':'v','f':'u',
'g':'t','h':'s','i':'r','j':'q','k':'p','l':'o',
'm':'n','n':'m','o':'l','p':'k','q':'j','r':'i',
's':'h','t':'g','u':'F','v':'e','w':'d','x':'c', 'y': 'b',
'z': 'a'
}
#Creatingconvertedoutput
converted_data = ""
foriinrange(0,len(data)):
if data[i] in conversion_code.keys():
converted_data+=conversion_code[data[i]]
else:
converted_data+=data[i]
#Printingconvertedoutput
print(converted_data)
Output
Dvoxlnvgl
6d)Plotahistogram ofwordsaccording totheir lengthfromtext readfromafile
defsplitString(str): l1
= []
s = [Link]( )
forwordsins:
[Link](len(words))
print(l1)
#Maincode
# declare string and assign value
frommatplotlibimportpyplotasplt
import numpy as np
str="HelloWorldHowareyou?ProgramexecutionstartsatPreprocessordirectives startsModulo
operatorcannotbeusedANSIexpansionASCIIexpansionClanguagedeveloppedbyFormat"
Page 22
KODAD INSISTUTE OF TECHNOLOGY AND SCIENCE FOR WOMEN
Page 23
KODAD INSISTUTE OF TECHNOLOGY AND SCIENCE FOR WOMEN
#callthefunction
splitString(str)
a= [Link](splitString(str))
#Creatinghistogram
fig,ax=[Link](figsize =(10,7))
[Link](a,bins=[0,4,8])
#Showplot
[Link]()
Cycle2:
7. HowtoInstallanOperatingSystemonaRaspberryPi
YourRaspberryPidoesn'tcomewithanoperatingsystempre-installed.
BeforeyoueventhinkaboutdownloadinganoperatingsystemforyourRaspberryPi,youneedtomakesureyou have the right
storage media. When choosing an SD card to buy you may find that a 32GB card is almost as affordable.
SeveraltoolsareavailablethatcanwriteaRaspberryPioperatingsystemtoanSDcard Installation
usingPiImager
AvailablefromtheofficialRaspberryPiwebsite,RaspberryPiImagerisautilitythatwritesanoperatingsystem to your
Pi's SD card.
Visit:[Link]->Selectsoftware->SelecttheOSinstallationusingRaspberryPiimager Once
imager is started select the OS and storage then press write button.
Butthisprocedurtakeslongtimeandsometimes eventhesystemmay hang.
Toavoidthisweusesecondapproach.
Installation using Image file
At firstdownload the Raspberry PiOS image into the system which is very big image from internet.(type
raspberryPiOSwithdesktopandrecommended softwareanddownloadwhichwillbedownloadedaszipfile. Extract
the zip file and store it on your computer.)
OnceimagerisstartedselecttheCustomoptionforOSselectingOSimageanduploadfromyour computer
DCollegeofEngineeringforWomen
Page 24
KODAD INSISTUTE OF TECHNOLOGY AND SCIENCE FOR WOMEN
Selectstorage(SDcard)towhichyouwanttowritethenpressWritebutton,whichwritesorburnttothememory card.
TakethatcardandinserttoRasberrypicomputerwhichmakes RaspberryPitoputinto.
8. AccessingGPIOPinsusing Python
a) InstallingGPIOZero library
GPIOZeroisinstalled bydefaultintheRaspberryPiOSdesktopimage,andtheRaspberryPiDesktop image for
PC/Mac, both available from [Link].
1. Updatetherepositorieslistusing
sudo aptupdate
2. Install thepackagefor Python3
sudo apt install python3-gpiozero (or)
for Python2
sudoaptinstallpython-gpiozero
b) BlinkinganLEDconnectedtooneofGPIOpin
Toinitialize theGPIOportsontheRaspberryPiweneedtofirstimportthePythonlibrary,theinitializethe library and
setup pin 8 as an output pin.
Initializationcode:
[Link] #ImportRaspberryPi GPIOlibrary
from time import sleep #Importthesleepfunctionfromthetimemodule
GPIO. setwarnings(False) # Ignore warning for now
[Link]([Link])#Usephysicalpinnumbering
[Link](8,[Link],initial=[Link]) #Setpin8to beanoutput pinandset initialvaluetolow(off)
LEDblinkcode:
while True: #Runforever
GPIO. output(8, [Link]) # Turn on
sleep(1) #Sleepfor1second
GPIO. output(8, [Link]) # Turn off
sleep(1) #Sleep for1 second
Page 25
KODAD INSISTUTE OF TECHNOLOGY AND SCIENCE FOR WOMEN
Combinebothinitializationand [Link] below
c) AdjustingthebrightnessofanLED
import [Link] as GPIO
importtime
#Led1onmyBoard led
= 11
[Link]([Link])
[Link](led,[Link]) #
50Hz PWM Frequency
pwm_led=[Link](led,50)
#FullBrightness,100%DutyCycle
pwm_led.start(100)
try:
whileTrue:
duty_s=raw_input("EnterBrightnessValue(0to100):") #
Convert into Integer Value
duty = int(duty_s)
pwm_led.ChangeDutyCycle(duty)
[Link](0.5)
except KeyboardInterrupt:
print"ExitingProgram"exce
pt:
print"ErrorOccurs,ExitingProgram"fina
lly:
[Link]()
Page 26
KODAD INSISTUTE OF TECHNOLOGY AND SCIENCE FOR WOMEN
DCollegeofEngineeringforWomen
Page 27
KODAD INSISTUTE OF TECHNOLOGY AND SCIENCE FOR WOMEN
c)AdjustingthebrightnessofanLED(0to100,where100meansmaximumbrightness)usingthein-builtPWM wavelength.
constintLED_PIN=5;
const int ON_TIME = 1000;
constintOFF_TIME=1000;
voidsetup(){
pinMode(LED_PIN,OUTPUT);
}
voidloop(){
digitalWrite(LED_PIN,HIGH); delay(
ON_TIME );
digitalWrite(LED_PIN,LOW);
delay( OFF_TIME );
}
9)Collecting SensorData
[Link]
import csv
import time, datetime
fromtimeimportsleep
import Adafruit_DHT
import [Link]
#initialize GPIO
[Link](False)
[Link]([Link])
[Link]()
#setupDHT sensor
dht_sensor=Adafruit_DHT.DHT11
dht_pin = 7
#global variables
datafile ="/home/pi/Desktop/Temp_Humid.csv"
#mainfunction-willtaketemp,humidityandtimestampandwritetocsvevery10s def
main():
i= 1
Page 28
KODAD INSISTUTE OF TECHNOLOGY AND SCIENCE FOR WOMEN
while(1):
print("Beginningcycle"+str(i))
data = get_data()
add_to_file(data)
sleep(10)
print("Endofcycle"+str(i)) i
= i+1
#gettempandhumidityandaddto'data'dictionary def
get_data():
now=[Link]()
humidity,temp=Adafruit_DHT.read(dht_sensor,dht_pin) if
humidity is not None and temp is not None:
data={'timestamp':str([Link]("%Y%m%d_%H-%M-%S")),'temperature':temp,'humidity':humidity}
print(data)
return(data)
#writetemp,humidityandtimestampstocsvfile def
add_to_file(data):
[Link](datafile):#[Link],appendsvaluesfordictionaryundercorresponding header
in a new line
with open(datafile, 'a', newline='') as csvfile:
fieldnames=['Time','Temperature','Humidity']
data_writer=[Link](csvfile,fieldnames=fieldnames,delimiter='',quotechar='|',
quoting=csv.QUOTE_MINIMAL)
data_writer.writerow({'Time':data['timestamp'],'Temperature':data['temperature'],'Humidity':
data['humidity']})
else:#createsfile(thathasbeencheckedanddoesnotyetexist)andaddsheadersandvaluesforall3keysin dict
with open(datafile, 'w', newline='') as csvfile:
fieldnames=['Time','Temperature','Humidity']
data_writer=[Link](csvfile,fieldnames=fieldnames,delimiter='',quotechar='|',
quoting=csv.QUOTE_MINIMAL)
data_writer.writeheader()
data_writer.writerow({'Time':data['timestamp'],'Temperature':data['temperature'],'Humidity':
data['humidity']})
if name =="main":
main()
Page 29
KODAD INSISTUTE OF TECHNOLOGY AND SCIENCE FOR WOMEN
VivaQuestions:
1. WhatisPython?
Pythonisahigh-levelandobject-orientedprogramminglanguagewithunifiedsemanticsdesignedprimarilyfor
[Link](RAD)asit offers
options such as dynamic binding and dynamic typing.
2. Whatarethe benefits ofPython?
ThebenefitsofPythonare asfollows:
• SpeedandProductivity:UtilizingtheproductivityandspeedofPythonwillenhancetheprocesscontrol
capabilities and possesses strong integration.
• ExtensiveSupportforLibraries: Pythonprovidesalargestandardlibrarythatincludesareassuchas
operating system interfaces, web service tools, internet protocols, and string protocols. Most of the
programming tasks are already been scripted in the standard library which reduces effort and time.
• User-friendlyDataStructures:Pythonhasanin-builtdictionaryofdatastructuresthatareusedtobuild fast
user-friendly data structures.
• ExistenceofThirdPartyModules:Thepresenceofthird-partymodulesinthePythonPackageIndex (PyPI)
will make Python capable to interact with other platforms and languages.
• EasyLearning:Pythonprovidesexcellentreadabilityandsimplesyntaxestomakeiteasyforbeginnersto learn.
3. Whatarethekeyfeatures ofPython?
Thefollowingarethesignificant featuresofPython,andtheyare:
• InterpretedLanguage: Pythonisaninterpreted languagethatisusedtoexecutethecodelinebylineata time.
This makes debugging easy.
• HighlyPortable:PythoncanrunondifferentplatformssuchasUnix,Macintosh,Linux,Windows,andso on. So,
we can say that it is a highly portable language.
• Extensible: ItensuresthatthePythoncodecanbecompiledonvariousotherlanguagessuchasC,C++, and so
on.
• GUIprogrammingSupport:ItimpliesthatPythonprovides supporttodevelopgraphicaluser interfaces
4. WhattypeoflanguageisPython?ProgrammingorScripting?
Pythonissuitableforscripting,butingeneral,itisconsideredageneral-purposeprogramminglanguage.
5. Whataretheapplicationsof Python?
Theapplications ofPythonareasfollows:
• GUIbaseddesktopapplications
• Imageprocessing applications
• BusinessandEnterprise applications
• Prototyping
• Webandwebframeworkapplications
BVRITHYDERABADCollegeofEngineeringforWomen
Page 30
KODAD INSISTUTE OF TECHNOLOGY AND SCIENCE FOR WOMEN
6. Whatarethetwomajorloopstatements?
for and while
7. Whatdoyouunderstandbythe termPEP8?
[Link] about how to
format your Python code for maximum readability.
8. HowmemorymanagementisdoneinPython?
• InPythonmemorymanagement [Link] all the
data structures and objects. The interpreter has access to the private heap and the programmer cannot
access this private heap.
• [Link] access for
some tools is provided by core API for programmers to code.
• Thebuilt-ingarbagecollectorinPythonisusedtorecyclealltheunusedmemorysothatitcanbe available
for heap storage area.
9. Whatarethebuilt-intypesavailableinPython?
Thebuilt-intypesinPythonareasfollows:
• Integer
• Complexnumbers
• Floating-pointnumbers
• Strings
• Built-infunctions
10. WhatarePythonDecorators?
DecoratoristhemostusefultoolinPythonasitallowsprogrammerstoalterthechangesinthebehaviorofclass or function.
Page 31