r22 Applied Python Lab Updated
r22 Applied Python Lab Updated
ON
APPLIED PYTHON PROGRAMMING
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.
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.
SYLLABUS
CYCLES PROGRAMS
1. DownloadingandInstallingPythonand Modules
a) Python3on Linux
FollowtheinstructionsgivenintheURLhttps://docs.python-guide.org/starting/
install3/linux/
b) Python3on Windows
Follow the instructions given in the URL
https://docs.python.org/3/using/windows.html(Pleaserememberthat Windows
installation of Python is harder!)
c) pip3onWindows andLinux
Install the Python package installer by following the
instructions given in the URL
https://www.activestate.com/resources/quick-reads/how-to-
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
10.CollectingSensor 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
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”:
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 get-pip.py from
<https://bootstrap.pypa.io/>
You can also use the curl command to download get-pip.py:
curlhttps://bootstrap.pypa.io/get-pip.py-oget-pip.py
CDintothedirectorywhereget-pip.pywasdownloadedto,andenterthefollowingcommandtoinstallpip3andits dependencies:
python3get-pip.py
Youcanverifythatpip3isinstalledbynavigatingtothedefaultpip3installationdirectory,eg.C:\python38\scripts\, and enter:
pip3–version
ToinstallNumPywiththe packagemanagerforPython3,run:
pip3installnumpy
ToinstallSciPywiththepackagemanagerforPython3,run:
pip3installscipy
1e)Installingjupyterlab
JupyterLabrequiresPython3.3orgreater.Python'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
2.BaiscPrograms
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)
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("myfile.txt","w")
L=["ThisisDelhi\n","ThisisParis\n","This isLondon\n"]
#\nisplacedtoindicateEOL(EndofLine)
file1.write("Hello \n")
file1.writelines(L)
file1.close()#tochangefileaccessmodes
file1=open("myfile.txt","r+")
print("OutputofReadfunctionis") print(file1.read())
print()
#seek(n)takesthefilehandletothenth #
bite from the beginning.
file1.seek(0)
print("OutputofReadlinefunctionis")
print(file1.readline())
print()
file1.seek(0)
#Toshowdifferencebetweenreadandreadline
print("Output of Read(9) function is ")
print(file1.read(9))
print()
file1.seek(0)
print("OutputofReadline(9)functionis")
print(file1.readline(9))
file1.seek(0)
#readlines function
print("OutputofReadlinesfunctionis")
print(file1.readlines())
print()
Page18
Page 11
KODAD INSISTUTE OF TECHNOLOGY AND SCIENCE FOR WOMEN
file1.close()
3b)Defineabooleanfunctionispalindrome(<input>)
def isPanlindrome(num):
returnint(num!=0)and((num%10)*\
(10**int(math.log(num,10)))+\
rev(num// 10))
#Readingnumber
test_number=input(“Enteranynumber”)
#printingtheoriginalnumber
print("The originalnumber is:"+str(test_number))
#usingmath.log()+recursion+listcomprehension #
for checking a number is palindrome
res=test_number== isPalindrome(test_number)
#printing result
print("Isthe numberpalindrome?:"+str(res))
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=math.exp(-((x-m)**2)/2*(s**s))/((2*math.pi*s)**0.5) return
result
Page 12
KODAD INSISTUTE OF TECHNOLOGY AND SCIENCE FOR WOMEN
print(solve(4,2))
4b)Writeaprogramthatadds,subtractsandmultipliestwomatrices.Provideaninterfacesuchthat,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 = np.dot(mat1,mat2)
#printresultedmatrix
print(res)
Page 13
KODAD INSISTUTE OF TECHNOLOGY AND SCIENCE FOR WOMEN
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"}
importmatplotlib.pyplotasplt import
csv
X= []
Y= []
withopen('GFG.txt','r')asdatafile:
plotting=csv.reader(datafile,delimiter=',')
for ROWS in plotting:
X.append(int(ROWS[0]))
Y.append(int(ROWS[1]))
plt.plot(X, Y)
plt.title('LineGraphusing CSV')
Page 15
KODAD INSISTUTE OF TECHNOLOGY AND SCIENCE FOR WOMEN
plt.xlabel('X')
plt.ylabel('Y')
plt.show()
Output:
importmatplotlib.pyplotasplt
import numpy as np
X,Y=np.loadtxt('GFG.txt',delimiter=',',unpack=True)
plt.bar(X,Y)
plt.title('LineGraphusingNUMPY')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()
Output:
Page 16
KODAD INSISTUTE OF TECHNOLOGY AND SCIENCE FOR WOMEN
EXAMPLE-2
importnumpyasnp
importmatplotlib.pyplotasmp
np.random.seed(12)
x=np.linspace(-20,20,10)
y=2*x+5
coeff=np.polyfit(x,y,2)
xn=np.linspace(-20,20,100)
yn = np.poly1d(coeff)
mp.plot( 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.
Usetheplt.hist()methodtoplotahistogram.
Compute and draw the histogram of *x*.
Wecanpassn-Dimensionalarraysinthehistargumentalso. To
show the plotted figure, use the plt.show() method.
Example
frommatplotlibimportpyplotasplt
x =[300, 400, 500, 2000, 10]
plt.hist(x,10)
plt.show()
Output
Page 17
KODAD INSISTUTE OF TECHNOLOGY AND SCIENCE FOR WOMEN
6a)Readtextfromafileandprintthenumberoflines,wordsandcharacters
METHOD-1
Thisversionoftheprogramcountsthenumberoflines,wordsandcharacters(includingspaces)using string
methods.
Solution algorithm:
Ateachiterationtheforcycleextractsthenextlinefromthefile.Thefollowingactionstakeplaceinthe body of the
cycle:
Thecounteroflines isincrementedby1.
Thestringissplitintowordsusingthe splitmethod.Thelenfunctioncountsthenumberofwordsinthelist 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 lenfunction.Theresultingvalueisaddedtothesymbolcounter.
Thetext file:
onetwothree city
town
bigsmall
Codeoftheprogram:
file= open('text.txt')
lines=0
words=0
symbols=0
forlineinfile:
lines += 1
words += len(line.split())
symbols+=len(line.strip('\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 forsolvingtheproblem.Wedonotusethe lenfunctionandstring methods.
Theeachlineisscannedcharacterbycharacter.Inthiscase,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
insidethewordornot.Ifanon-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('text.txt')
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:
ifsub.startswith(ele):
flag = True
break
if flag:
res.append(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(sub.startswith(ele)foreleinvow)
ifflag:
res.append(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(s.find("a")==0ors.find("e")==0ors.find("i")==0ors.find("e")==0ors.find("u")==0): return
True
returnFalse
res = []
for sub in test_list:
if(vowelstart(sub)):
res.append(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
Page 22
KODAD INSISTUTE OF TECHNOLOGY AND SCIENCE FOR WOMEN
Page 23
KODAD INSISTUTE OF TECHNOLOGY AND SCIENCE FOR WOMEN
#callthefunction
splitString(str)
a= np.array(splitString(str))
#Creatinghistogram
fig,ax=plt.subplots(figsize =(10,7))
ax.hist(a,bins=[0,4,8])
#Showplot
plt.show()
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:www.raspberrypi.org->Selectsoftware->SelecttheOSinstallationusingRaspberryPiimager Once
imager is started select the OS and storage then press write button.
Butthisprocedurtakeslongtimeandsometimes eventhesystemmay hang.
Toavoidthisweusesecondapproach.
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 raspberrypi.org.
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:
ImportRPi.GPIOasGPIO #ImportRaspberryPi GPIOlibrary
from time import sleep #Importthesleepfunctionfromthetimemodule
GPIO. setwarnings(False) # Ignore warning for now
GPIO.setmode(GPIO.BOARD)#Usephysicalpinnumbering
GPIO.setup(8,GPIO.OUT,initial=GPIO.LOW) #Setpin8to beanoutput pinandset initialvaluetolow(off)
LEDblinkcode:
while True: #Runforever
GPIO. output(8, GPIO.HIGH) # Turn on
sleep(1) #Sleepfor1second
GPIO. output(8, GPIO.LOW) # Turn off
sleep(1) #Sleep for1 second
Page 25
KODAD INSISTUTE OF TECHNOLOGY AND SCIENCE FOR WOMEN
c) AdjustingthebrightnessofanLED
import RPi.GPIO as GPIO
importtime
#Led1onmyBoard led
= 11
GPIO.setmode(GPIO.BOARD)
GPIO.setup(led,GPIO.OUT) #
50Hz PWM Frequency
pwm_led=GPIO.PWM(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)
time.sleep(0.5)
except KeyboardInterrupt:
print"ExitingProgram"exce
pt:
print"ErrorOccurs,ExitingProgram"fina
lly:
GPIO.cleanup()
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;
voidsetup(){
pinMode(LED_PIN,OUTPUT);
}
voidloop(){
digitalWrite(LED_PIN,HIGH); delay(
ON_TIME );
digitalWrite(LED_PIN,LOW);
delay( OFF_TIME );
}
9)Collecting SensorData
importRPi.GPIOasGPIO
import csv
import time, datetime
fromtimeimportsleep
import Adafruit_DHT
import os.path
#initialize GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.cleanup()
#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=datetime.datetime.now()
humidity,temp=Adafruit_DHT.read(dht_sensor,dht_pin) if
humidity is not None and temp is not None:
data={'timestamp':str(now.strftime("%Y%m%d_%H-%M-%S")),'temperature':temp,'humidity':humidity}
print(data)
return(data)
#writetemp,humidityandtimestampstocsvfile def
add_to_file(data):
ifos.path.isfile(datafile):#checksiffileexists.ifyes,appendsvaluesfordictionaryundercorresponding header
in a new line
with open(datafile, 'a', newline='') as csvfile:
fieldnames=['Time','Temperature','Humidity']
data_writer=csv.DictWriter(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=csv.DictWriter(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
developingappsandtheweb.ItisthecorelanguageinthefieldofRapidApplicationDevelopment(RAD)asit offers
options such as dynamic binding and dynamic typing.
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:
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?
7. Whatdoyouunderstandbythe termPEP8?
8. HowmemorymanagementisdoneinPython?
• InPythonmemorymanagement isdoneusingprivateheapspace.Theprivateheapisthestorageareafor all the
data structures and objects. The interpreter has access to the private heap and the programmer cannot
access this private heap.
• ThestorageallocationforthedatastructuresandobjectsinPythonisdonebythememorymanager.The 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