Pspp Lab Manual
Pspp Lab Manual
LAB MANUAL
1
GE3171–PROBLEMSOLVINGANDPYTHONPROGRAMINGLABORATORY
ILISTOFEXPERIMENTS
EX.NO ListofExperiments
Developing flowcharts
a) ElectricityBilling,
b) RetailShopBilling,
1.
c) SinSeries,
d) Weight ofaMotorbike,
e) WeightofaSteelBar,
f) ComputeElectricalCurrentinThreePhaseACCircuit.
ProgramsUsingSimpleStatements
2. a) Exchangethevaluesoftwovariables,
b) Circulatethevaluesofnvariables,
c) Distancebetween two points.
ProgramsUsingConditionalsand IterativeStatements
3. a) NumberSeries
b) NumberPatterns
c) PyramidPattern
a) OperationsofLists(Itemspresentinalibrary/Componentsofacar/Materia
4. lsrequiredforconstruction ofabuilding)
b) OperationsofListsandTuples(Itemspresentinalibrary/Componentsofacar/
Materials required forconstruction ofabuilding)
a) OperationsofSets(Language,componentsofanautomobile,Elementsofacivil
5. structure,etc)
b) OperationsofDictionaries(Language,componentsofanautomobile,Elem
entsofacivil structure, etc)
ProgramsUsingFunctions
6. a) Factorial of aNumber
b) LargestNumberinalist
c) AreaofShape
Programs using Strings.
7. a) Reversing a String,
b) Checking Palindrome in a String,
c) Counting Characters in a String
d) Replacing Characters in a String
2
Programs Using modules and Python Standard Libraries
a) Pandas
8. b) Numpy
c) Matplotlib
d) Scipy
Programs using FileHandling.
9. a) Copyfrom onefiletoanother,
b) Wordcount
c) Longestword
ProgramsUsingExceptionhandling.
10. a) Dividebyzero error
b) Voter‟sagevalidity
c) Student mark range validation
11.
Exploring Pygame tool.
3
Ex.No1.A
Developing flowcharts for Electricity Billing
Date:
Aim:
To writeaalgorithm anddrawflowchartforElectricBilling.
Algorithm:
Step2:Read input n.
Step4: Check n<=200 is yes, then calculate amt= (n-100)*1.5 and go to step 7.If no go to step5
Step5: Check n<=500.If yes, then calculate amt=200+ (n-200)*3 and go to step7.If no go to step6
4
Flowchart:
Start
Readunits
Amount=100*0 Amount=
(100*0)+(200-
100)*3.5+(500-
200)*4.6+ (unit-
500)*6.6
Amount Amount =
=(100*0)+(unit- (100*0)+(200-
100)*1.5 100)*2+(unit-200)*3
PrintAmount
Stop
Result:
5
Ex.No 1.B
Developing flowcharts for Retail Shop Billing
Date:
Aim:
To write an algorithm and draw flowchart for Retail Shop Billing.
Algorithm:
Step1:Starttheprogram.
6
Flowchart:
Start
Tax=0.18
Rate_ of_item
Display Quantities
Rated Quantities
BillAmount=Cost+Cost*tax
Print BillAmount
stop
Result:
.
7
Ex.No1.C
Developing flowcharts for Sine Series
Date:
Aim:
To write an algorithm and draw flowchart for sine series.
Algorithm:
Step2:Readx, n
8
Flowchart:
Start
Read x, n
x=x*3.14159/180;
t=x;su
m=x;
i=1;i<=n;i++
t= (t*(-
1)*x*x)/(2*i*(2*i+1)
);sum=sum+t;
Printsumassine(x)
stop
Result:
9
Ex.No1.D
Developing flowcharts for Weight of a Motorbike
Date:
Aim:
To write an algorithm and draw flowchart for Weight of a Motorbike.
Algorithm:
10
Flowchart:
Start
Placethemotorbikeonweightcase
Readthescaleinkg
Initialize ADC=0
No Is
itdigitall
y
clear?
yes
Displayiton LCD
Stop
Result:
11
Ex.No 1.E
DevelopingflowchartsforWeightofaSteelBar
Date:
Aim:
To write an algorithm and draw flowchart for Weight of a Steel Bar.
Algorithm:
12
Flowchart:
Start
Input l&r
den=7800
wt=(math.pi*r*l*den)/10000
Print(wt)
stop
Result:
13
Ex.No 1.F
Aim:
To write an algorithm and draw flow chart for Electric Current in Three Phase AC Circuit.
Algorithm:
Step2:ComputeTotalVA
14
Flowchart:
Start
ReadTotal VA
Aline=TotalVA/(√3*Vline)
PrintAline
Stop
Result:
15
Ex.No 2.A
Aim
To write a python program to Exchange the values of two variables using simple statements.
Algorithm:
Step1: Start the program
Step 2: Declare the values of x and y
Step 3: Print before swaping x ,y
Step 4:compute x, y= y, x
Step 5: Print after swaping x , y
Step 6:stop the program.
Program
x=input(“enter the value of x”)
y=input(“enter the value of y”)
print(“before exchange of x,y”)
print(“x=”,x)
print(“y=”,y)
x,y=y,x
print(“after exchange of x,y”)
print(“x=”,x)
print(“y=”,y)
Output
Enter the value of x 23
Enter the value of y 45
Before exchange of x,y
x=23
y=45
After exchange of x,y
x=45
y=23
Result:
16
Ex.No 2.B
Circulate the Values of N Variable
Date:
Aim
To write a python program to Circulate the values of n variable using simple
statements.
Algorithm:
Step1:Start the program
Step2:Declare the value of n
Step3 : Get the elements in the list.
Step4:print circulating the elements of list
Step 5 : for circulate the values of n and for i in range (n+1)
Step6 : compute c=L[i:]+L[:i]
Step 7 : print circulation value of n
Step8 :stop theprogram .
Program:
n=int(input('Enter n:'))
L=[91,92,93,94,95]
print("Circulating the elements of list ", L)
for i in range(n+1):
c=L[i:]+L[:i]
print(“circulation”,i,’=’,c)
Output:
Enter n : 5
Circulating the elements of list[91,92,93,94,95]
Circulation 1 = [92, 93,94, 95,91]
Circulation 2=[93, 94,95,91,92]
Circulation 3=[94, 95,91,92,93]
Circulation4=[95, 91,92,93,94]
Circulation5 =[91,92,93,94,95]
Result:
17
Ex.No 2.C
Distance between two points using Simple Statements
Date:
Aim:
To write a python program to find distance between two variables.
Algorithm:
Step1:Start the program by importing math library.
Step2: Declare the values ofx1 ,y1,x2 ,y2.
Step 3 :Calulate the distance = math.sqrt((x2-x1)**2)+((y2-y1)**2))
Step4 : Print the distance between two points
Step5:Stop the program.
Program:
import math
x1=int(input("enter a x1 value:”))
x2=int(input("enter a x2 value:"))
distance=math.sqrt(((x2-x1)**2)+((y2- y1)**2))
Output:
enter a x1 value:9
enter a y1 value:8
enter a x2 value:3
enter a y2 value:4
distance between two points= 7.211102550927978
Result:
18
Ex.No 3.A
Programs Using Conditionals and Iterative Statements
Date: Number Series
Aim:
Algorithm:
Step1: Start the program
Step 2: Declare the value of n
Step3:Intialize sum =0,i=0
Step 4: Check the while condition i<=n and go to next step 5 else goto step 7.
Step 5: Increment the value of I and calculate the sum value sum = sum +i*I
Step6:Increment the I value i+=1
Step 7: Print the sum value.
Step8: Stop the program.
Program:
n=int(input('Enteranumber:'))
sum=0
i=1
whilei<=n:
sum=sum+i*i
i+=1
print('Sum=',sum)
Output:
Enteranumber:10Su
m = 385
Result:
19
Ex.No 3.B
Programs Using Conditionals and Iterative Statements Number Pattern
Date:
Aim:
To write a python program to print Number Pattern.
Algorithm;
Step 1 : Start the program .
Step2:Definethevalueofn
Step 3 : Check the condition of for i in loop (1,n+1)
Step4: Next, check forkin range(n,i-1)
Step5 : print(““)
Step 6 : check the condition for j in range (1,1+1)
Step7 : print (““)
Step 8 : Check the last condition of for m in (i-1,0-1)
Step9 : Print (““)
Step10: print ()
Step11:stoptheprogram.
Program:
N = int(input("enter n value:"))
for i in range(1,N+1):
for k in range(N,i,-1):
print("",end='')
for j in range(1,i+1):
print(j,end='')
for m in range(i-1,0,-1):
print(m, end =' ')
print()
Output:
Enter nvalue:5
1
121
12321
1234321
123454321
Result:
20
Ex.No 3.C
Programs Using Conditionals and Iterative Statements Pyramid Pattern
Date:
Aim:
To write a python program to print Pyramid Pattern.
Algorithm:
Step1:Start the program.
Step2:Declare the value forn
Step 3; Check the condition for i in 1 to n+1
Step 4 : Next , check the condition for j in 0 to I
Step 5 : Print (*)
Step6 : Print ()
Step7:Stop theprogram.
Program:
# to print pyramid pattern1
n=int(input("enterthevalue:"))
fori in range(1, n+1):
for j in range(0, i):
print("*",end='')
print()
print(' ')
# to print pyramid pattern2
n=int(input("enterthevalue:"))
fori in range(1,n+1):
print(' '*(n-i), end='')
for j in range(1, i+1):
print('*',end='')
print()
print(' ')
# to print pyramid pattern3n=int(input("enter the value: " ) )
for i in range(1,n+1):
for j in range(1, n-i+2):
print('* ',end='')
print()
print(' ')
# to print pyramid pattern3
21
n=int(input("enter the value:"))
for i in range(1,n+1):
print(' '*(i-1), end='')
for j in range(1, n-i+2):
print('* ',end='')
print()
print(' ')
Output:
enterthevalue:5
*
**
***
****
*****
*
**
***
****
*****
*****
****
***
**
*
*****
****
***
**
*
Result:
22
Ex.No 4.A
Operations of List
Date:
Aim:
library =['Books','Periodicals','Newspaper','Manuscripts','Maps','Prints','Documents','Ebooks']
print('Library:',library)
print('first element:',library[0])
print('fourth element:',library[3])
print('index of \'Newspaper\':',library.index('Newspaper'))
library.sort()
print('after pop():',library);
23
print('after insert:',library)
Output:
Library:['Books','Periodicals','Newspaper','Manuscripts','Maps','Prints','Documents','Ebooks']
firstelement:Books
fourthelement:Manuscripts
Items in Library from 0 to 4 index:['Books', 'Periodicals', 'Newspaper','Manuscripts',
indexof'Newspaper':2
Poppedelementsis:Prints
'Periodicals']NumberofElements inLibrarylist:1
Result:
24
Ex.No 4.B
Operations of Tuple
Date:
Aim:
Program:
Output:
Components of a car: ('Engine', 'Battery', 'Alternator', 'Radiator', 'Steering', 'Break', 'Seat Belt')
index of 'Alternator': 2
Number of Elements in Car Tuple : 1
Length of Elements in Car Tuple : 7
Result:
25
Ex.No 5.A
Operations of Set
Date:
Aim:
Step 6: Compare two set of elements using Set symmetric difference operation.
Program:
S1 = {'Pitch', 'Syllabus', 'Script', 'Grammar', 'Sentences'};
S2 = {'Grammar', 'Syllabus', 'Context', 'Words', 'Phonetics'};
print("Union of S1 and S2 is ",S1 | S2)
print("Intersection of S1 and S2 is",S1 & S2)
print("Difference of S1 and S2 is",S1 - S2)
print("Symmetric difference of S1 and S2 is",S1 ^ S2)
Output:
Result:
26
Ex.No 5.B
Operations of Dictionaries
Date:
Aim:
Algoithm:
Program:
civ={'name':'civil structure',2:'floor',3:'stairs',4:'beams',5:'walls'}
print(civ)
print(civ['name'])
print(civ.get(4))
print(len(civ))
print('name' in civ)
print(1 in civ)
print(civ.values())
print(civ.keys())
Output:
{'name':'civilstructure',2:'floor',3:'stairs',4:'beams',5:'walls'}civilstr
ucture
beams
5
True
False
dict_values(['civil structure', 'floor', 'stairs', 'beams',
'walls'])dict_keys(['name',2, 3, 4, 5])
Result:
27
Ex.No 6.A
Factorialof aNumberUsingRecursiveFunction
Date:
Aim:
Towriteapythonprogramto FactorialofanumberusingRecursive Function.
Algorithm:
Step1:Starttheprogram.
Step2:Gettheinput n.
Step3:Definethefunction fact(x).
Step4: Ifx==1,thenreturn1.Otherwisereturn(x*fact(x-1)).
Step5:Printthefactorialofanumber.
Step6:Stoptheprogram.
Program:
def fact(x):
if x==1:
return 1
else:
return(x*fact(x-1))
n=int(input(“Enter a number:”))
Output:
Enteranumber:5
Result:
Thus,thegiven programsuccessfullyexecutedandpracticallyverified.
28
Ex.No 6.B
FindingLargestNumberinaListusingFunction
Date:
Aim:
Towriteapythonprogram tofindthelargest numberinalistusingfunction.
Algorithm:
Step1:Starttheprogram.
Step2:Gettheinput num.
Step3:Usingforloopwhichhastherange(1,num+1).Readtheelementinthelist.
Step4:Definethefunction myMax(list1)andfindthelargestnumberinalist.
Step5:Printthelargest numberinalist.
Step6:Stoptheprogram.
Program:
defmyMax(list1):
print(“Largest element is:”, max(list1))
list1=[]
num=int(input("Enter a number of elements in a list:"))
fori in range(1,num+1):
ele=int(input("Enter elements:"))
list1.append(ele)
print(myMax(list1))
Output:
Enter a number of elements in a
list:5Enterelements:23
Enter
elements:45Enter
elements:87Enter
elements:67Enter
elements:3987
Result:
Thus,thegiven programsuccessfullyexecutedandpracticallyverified.
29
Ex.No 6.C
FindingAreaof aShapeusing Function
Date:
Aim:
Towriteapythonprogramto findtheareaofthedifferentshapesusingfunction.
Algorithm:
Step1:Starttheprogram.
Step2:Definethefunctionsquare.
Step3:Gettheinput valueofsideandprinttheareaofsquare.(i.e.,side*side)
Step4:Definethefunctionrectangle.
Step5:Gettheinput valueoflandbandprinttheareaofrectangle. (i.e., l*b)
Step6:Definethefunctiontriangle.
Step7:Gettheinputvalue band handprint theareaoftriangle.(i.e.,0.5*b*h)
Step8:Definethefunctioncircle.
Step9:Gettheinput valuerandprintareaofcircle.((i.e.,3.14*r**2)
Step10:Print1.square,2.rectangle,3.triangleand4.circle.
Step11:Getthenvalueas input.
Step12:Computeifn==1,thencall thefunctionsquare. Ifnogotonextstep.
Step13: If n==2,then call the function rectangle. If no go to next
step.Step14: If n==3,then call the function triangle. If no go to next
step.Step15: If n==4,then call the function circle. Otherwise go to next
step.Step16:Print invalid choice.
Step17:Stoptheprogram.
Program:
def square():
side=int(input("Enter the side of a square:"))
print("Area of a square:", side*side)
def rectangle():
l=int(input("Enter the length of a rectangle:"))
b=int(input("Enter the breath of a rectangle:"))
print("Area of a rectangle:", l*b)
def triangle():
b=int(input("Enter the base of a triangle:"))
h=int(input("Enter the height of a triangle:"))
print("Area of a triangle:", b*h*0.5)
def circle():
r=float(input("Enter the radius of a circle:"))
print("Area of a circle:", 3.14*r**2)
30
print("1. Square 2. Rectangle 3. Triangle 4. Circle")
n=int(input("Enter your choice:"))
if n==1:
square()
elif n==2:
rectangle()
elif n==3:
triangle()
elif n==4:
circle()
else:
print(“Invalid Choice”)
Output:
CircleEnteryour choice:4
circle:14Areaof
acircle:615.44
CircleEnteryour choice:2
180.00
Result:
Thus,thegiven programsuccessfullyexecutedandpracticallyverified.
31
Ex.No 7.A
ReversingaString
Date:
Aim:
Towriteapythonprogramto reverseastring.
Algorithm:
Step1:Read theinput str.
Step2: Using the colon operator, the string get
reversed.Step3:Printthereversedstring.
Program:
str=input("Enter the string:")
rev=str[::-1]
print("The reversed string is:",rev)
Output:
Enterthestring:python
Thereversedstringis:nohtyp
Result:
Thus,thegiven programsuccessfullyexecutedandpracticallyverified.
32
Ex.No 7.B
CheckingPalindromeinaString
Date:
Aim:
Towriteapythonprogram tocheckwhetherthe givenstringisPalindrome.
Algorithm:
Step1:Starttheprogram.
Step4:Stoptheprogram.
Program:
Output:
AMMAGiven string is
PROGRAMGivenstringisnotp
alindrome
Result:
Thus,thegiven programsuccessfullyexecutedandpracticallyverified.
33
Ex.No 7.C
CountingCharactersinaString
Date:
Aim:
Towriteapythonprogramtocount acharacterinastring.
Algorithm:
Step1:Gettheinputstrand ch.
Step2: Using the count method find the number of characters in str and assign it as
val.Step3:Print val
Step4:stoptheprogram.
Program:
str=input("Enter the string")
ch=input("Enter the character:")
val=str.count(ch)
print(val)
Output:
Enter the string: PYTHON
PROGRAMMINGEnterthecharacter: G
2
Result:
Thus,thegivenprogramsuccessfullyexecutedand practicallyverified.
34
Ex.No 7.C
ReplaceCharactersin aString
Date:
Aim:
Towriteapythonprogramto replacea characterinastring.
Algorithm:
Step1:Starttheprogram.
Step2:Gettheinput str,oldandnew.
Step4: By using replace method,replace old string by new
stringStep4:Print (str.replace(old,new))
Step5:Stoptheprogram
Program:
str=input("Enter the string:")
print(str.replace(old,new))
Output:
Enter the string:PYTHON
PROGRAMMINGEntertheold
string:PYTHON
Enterthenewstring:C PROGRAMMING
Result:
Thus,thegiven programsuccessfullyexecutedandpracticallyverified.
35
Ex.No 8.A
ComparetheElementsoftheTwoPandasSeriesusingPandasLibrary
Date:
Aim:
Towriteapythonprogramto comparetheelements ofthetwoPandas seriesusingpandaslibrary.
Algorithm:
Step1:Starttheprogram.
Step2: ImportthelibraryfunctionPandas.
Step3: Give the inputs as ds1, ds2 in the form of
lists.Step4:ds1is interpreted asSeries1.
Step5:ds2isinterpretedasSeries2.
Step6:CompareSeries1andSeries2andfollowthesteps6.1,6.2,6.3.
6.1.ds1==ds2
6.2.ds1>ds26
.3.ds1<ds2
Program:
import pandas as pd
ds1 = pd.Series([2, 4, 6, 8, 10])
ds2 = pd.Series([1, 3, 5, 7, 10])
print("Series1:")
print(ds1)
print("Series2:")
print(ds2)
print("Compare the elements of the said Series:")
print("Equals:")
print(ds1 == ds2)
print("Greater than:")
print(ds1 > ds2)
print("Less than:")
print(ds1 < ds2)
Output:
Series1:
02
14
26
38
4 10
dtype:int64
36
Series2:
01
13
25
37
4 10
dtype:int64
Comparetheelements of thesaidSeries:
Equals:
0 False
1 False
2 False
3 False
4 Truedtype:
boolGreatert
han:
0 True
1 True
2 True
3 True
4 Falsedty
pe:
boolLessth
an:
0 False
1 False
2 False
3 False
4 Falsedty
pe:bool
Result:
Thus,thegiven programsuccessfullyexecutedandpracticallyverified.
37
Ex.No 8.B
ToTestwhetherNoneof theElementsof aGiven
ArrayisZeroUsingNumpyLibrary
Date:
Aim:
Towriteapythonprogram totest whethernoneof theelements ofa givenarrayis
zero usingnumpylibrary.
Algorithm:
Step1:Start theprogram.Step2:Import
the numpy library as
np.Step3:Givethe input xasarray.
Step4:PrintxasOriginalArray.
Step5:Check whether any of the elements is zero or
not.Step6:print the statement.
Step7:Closetheprogram.
Program:
importnumpy as np
x = np.array([1, 2, 3, 4])
print("Original array:")
print(x)
print("Test if none of the elements of the said array is zero:")
print(np.all(x))
x = np.array([0, 1, 2, 3])
print("Original array:")
print(x)
print("Test if none of the elements of the said array is zero:")
print(np.all(x))
Output:
Originalarray:
[1 2 3 4]
Testif noneofthe elementsof the said arrayis zero:
True
Originalarray:
[0 1 2 3]
Testif noneofthe elementsof the said arrayis zero:
False
Result:
Thus,thegiven programsuccessfullyexecutedandpracticallyverified.
38
Ex.No 8.C
ToPlotaGraphUsingMatplotlibLibrary
Date:
Aim:
Towriteapythonprogram toplotagraphusingmatplotliblibrary.
Algorithm:
Step1:Starttheprogram.
Step2:Importmatplotlib
andnumpyaspltandnprespectively.Step3:Giveinputxpointsand
ypoints intheformofarray.
Step4:Now plot the points using plt.plot
function.Step5:Display the graph using
plt.show() fuctionStep6:Closethe program.
Program:
importmatplotlib.pyplot as
pltimport numpyas np
xpoints = np.array([0,
6])ypoints = np.array([0,
250])plt.plot(xpoints,
ypoints)plt.show()
Output:
Result:
Thus,thegiven programsuccessfullyexecutedandpracticallyverified.
39
Ex.No 8.D
ToReturn theSpecifiedUnitinSecondsUsingScipyLibrary
Date:
Aim:
Towriteapythonprogramto returnthespecifiedunit inseconds(e.g.hour
returns3600.0)usingscipylibrary.
Algorithm:
Step1:Starttheprogram.
Step2:Importscipyasconstants.
Step3:PrintMinutes,Hours,Days,Weeks,Years, Julian_Year
Program:
fromscipy import
constantsprint(constants.mi
nute)print(constants.hour)pr
int(constants.day)print(cons
tants.week)print(constants.y
ear)print(constants.Julian_y
ear)Output:
60.0
3600.0
86400.0
604800.0
31536000.0
31557600.0
Result:
Thus,thegiven programsuccessfullyexecutedandpracticallyverified.
40
Ex.No 9.A
COPY FROMONEFILETOANOTHERFILE
Date:
Aim:
Towriteapythonprogramtocopyfromonefiletoanotherfile.
Algorithm:
Step-1-Starttheprogram
Step-2- Get the source and destination file name as
input.Step-3-Read thesourcefileusingread
Step-4-Writeon thedestination file
Step-5- The file copy from the source file to the destination file using copy file
module.Step-6-Ifthefileissuccessfullycopied,thenshow„filecopiedsuccessfully‟
Step-7- Open the destination file and
read.Step-8-Close thefile.
Step-9-Stoptheprogram.
Program:
sfn=input("Entersourcefilename:")
dfn = input("Enter destination file name:
")sf=open(sfn,"r")
df = open(dfn,
"w")str =
sf.read()df.write(st
r)
print("File copied
successfully!")sf.close()
df.close()
sf2 = open(dfn,
"r")str2 =
sf2.read()print(str
2)sf2.close()
Output:
Enter source file name:
file1.txtEnter destination file name:
file2.txtFilecopied successfully!
Sunflower
JasmineR
oses
Result:
Thus,thegiven programsuccessfullyexecutedandpracticallyverified.
41
Ex.No 9.B
WORDCOUNTFROMFILE
Date:
Aim:
Towriteapythonprogramtocountnumberofwordinafile.
Algorithm:
Step-1:Starttheprogram.
Program:
file = open("F:\Data.txt",
"rt")data=file.read()
words=data.split()
print('Numberofwordsintextfile:',len(words))
Output:
Number ofwords in textfile: 36
Result:
Thus,thegiven programsuccessfullyexecutedandpracticallyverified.
42
Ex.No 9.C
FindingLongestWordinaFile
Date:
Aim:
Towriteapythonprogramtofind thelongest wordinafile.
Algorithm:
Step-1-Starttheprogram.
filename.Step-3-Endthe program
Subfunction()
Step-1-definethefunctionlongest_word()
word.Step-4-Displaythelongest word.
Step-5-Endtheprogram.
Program:
deflongest_word(filename):
with open(filename, 'r') as
infile:words =
infile.read().split()maxword=max(
words,key=len)
returnmaxword
print(longest_word('ex9a.py'))
Output:
['collection']
Result:
Thus,thegiven programsuccessfullyexecutedandpracticallyverified.
43
Ex.No 10.A
DividebyZeroErrorusingExceptionHandling
Date:
Aim:
Towriteapythonprogramto handle divide yzero errorusingexception handling.
Algorithm:
Step-1- Start the
ProgramStep-2-
Getnum1,num2.
Step-3- Evaluate the result by
num1/num2.Step-4-print result.
Step-5- Otherwise display the
e.Step-6-Endtheprogram.
Program:
try:
num1=int(input("enter first number:"))
num2=int(input("enter second number:"))
result=num1/num2
exceptValueError as e:
print("invalid input")
exceptZeroDivisionError as e:
print(e)
else:
print(result)
Output:
enter first number:
33enter second
number:231.434782608
695652
Result:
Thus,thegiven programsuccessfullyexecutedandpracticallyverified.
44
Ex.No 10.B
VotersAgeValidityUsingExceptionHandling
Date:
Aim:
Towriteapythonprogramtocheckvotersagevalidity.
Algorithm:
Step-1- Start the program by defining main
function.Step-2-Get theageas input.
Step-3- Check the condition age>18, display eligible to vote, otherwise, display not
eligible.Step-4-if thetryblock isnot executed, exceptionblockget executed.
Step-5-Stoptheprogram.
Program:
def main():
try:
age=int(input("enter your age : "))
if age>18:
print("eligible to vote")
else:
print("not eligible to vote")
exceptValueError as err:
print("an error occured : ",err)
main()
Output:
enter your
age18noteligibleto
vote
enter your
age45eligibletov
ote
Result:
Thus,thegiven programsuccessfullyexecutedandpracticallyverified.
45
Ex.No 10.C
StudentMark RangeValidation
Date:
Aim:
Towriteapythonprogramto performstudentmarkrangevalidation.
Algorithm:
Step-1-Start theProgrambydefiningmainfunction.
Step-2- Get marks Step-3- using try Check if mark>=3 and mark<101 display pass and mark
isvalid,otherwisefail.
Step-4- Otherwise display the exception
block.Step-5-Stop theProgram.
Program:
def main():
try:
mark=int(input("Enter your mark:"))
if mark>=35 and mark<101:
print("pass and your mark is valid")
else:
print("fail and your mark is valid")
exceptValueError:
print("mark must be a valid number")
exceptIOError:
print("Enter correct valid mark")
except:
print("An Error occured")
main()
Output:
Enteryourmark:59
passandyourmarkisvalid
Enteryourmark:20
failandyourmarkisvalid
Enter yourmark:aa
markmust beavalidnumber
Result:
Thus,thegiven programsuccessfullyexecutedandpracticallyverified.
46
Ex.No 11
ExploringPygame
Date:
PYGAMEINSTALLATION
ToInstallPygameModuleSteps
1. Installpython 3.6.2intoC:\
2. Gotothislinktoinstallpygamewww.pygame.org/download.shtml
3. Click
pygame-1.9.3.tar.gz~2Manddownloadzarfile
4. ExtractthezarfileintoC:\Python36-32\Scriptsfolder
5. Open command
promptTypethefollowingcom
mand
C:\>py -m pip install pygame --
userCollectingpygame
Downloadingpygame-1.9.3-cp36-cp36m-win32.whl(4.0MB)
100%|████████████████████████████████|4.0MB
171kB/s
Installing collected
packages:pygameSuccessfull
y installedpygame-1.9.3
7. Now,pygameinstalledsuccessfully
47
8. Toseeifitworks,runoneoftheincludedexamplesinpygame-1.9.3
Opencommandprompt
Typethefollowing
C:\>cd Python36-32\Scripts\pygame-
1.9.3C:\Python36-32\Scripts\pygame-
1.9.3>cdexamples
C:\Python36-32\Scripts\pygame-
1.9.3\examples>aliens.pyC:\Python36-
32\Scripts\pygame-1.9.3\examples>
48
Ex.No 12
SimulateBouncingBallusingPygame
Date:
Aim:
Towriteapythonprogramtobouncingball inpygame.
Algorithm:
Step1:Starttheprogram.
Step2:Setscreensizeandbackgroundcolor.Step3:Se
tspeedofmovingball.
Step4: Createagraphicalwindowusingset_mode()Step5:
Setcaption.
Step6:LoadtheballimageandcreatearectangleareacoveringtheimageStep7:
Useblit() methodtocopy thepixel color of the ball
tothescreenStep8:Setbackgroundcolorofscreenanduseflip()methodto
makeallimagesvisible.
Step9:Movetheballinspecifiedspeed.
Step10:Ifballhitstheedgesofthescreenreversethedirection.
Step11: Createaninfinite loopandRepeat steps9and10untiluser quitstheprogram
Step12: Stoptheprogram
Program:
import sys,
pygamepygame.init
()
size = width, height = 700,
250speed=[1, 1]
background =255, 255,255
screen =
pygame.display.set_mode(size)pygame.displ
ay.set_caption("Bouncingball")ball
=pygame.image.load("ball.jpg")
ballrect =
ball.get_rect()while 1:
pygame.time.delay(2)
foreventinpygame.event.get():
ifevent.type == pygame.QUIT:
sys.exit()ballrect=ballrect.move(speed)
ifballrect.left< 0 or ballrect.right>
width:speed[0] = -speed[0]
49
ifballrect.top<0orballrect.bottom>height:
50
speed[1] = -
speed[1]screen.fill(backgro
und)screen.blit(ball,
ballrect)pygame.display.flip
()
ball.jpg
Output:
Result:
Thus,thegiven programsuccessfullyexecutedandpracticallyverified.
51