c# display pdf in browser : Add page numbers pdf SDK Library API wpf asp.net winforms sharepoint python-programming-an-introduction-to-computer-science11-part372

7.1. SIMPLEDECISIONS
103
Thebodyisjustasequenceofoneormorestatementsindentedundertheifheading.Inconvert2.py
therearetwoifstatements,bothofwhichhaveasinglestatementinthebody.
Thesemanticsoftheifshouldbeclearfromtheexampleabove. First,theconditionintheheading
isevaluated. Iftheconditionistrue,thesequenceofstatementsinthebodyisexecuted,andthencontrol
passestothenextstatementintheprogram.Iftheconditionisfalse,thestatementsinthebodyareskipped.
Figure7.2showsthesemanticsoftheifasaflowchart. Noticethatthebodyoftheifeitherexecutesor
yes
no
<condition> true?
<Body>
Figure7.2:Controlflowofsimpleif-statement
notdependingonthecondition.Ineithercase,controlthenpassestothenextstatementaftertheif.Thisis
aone-wayorsimpledecision.
7.1.2 FormingSimpleConditions
Onepointthathasnotyetbeendiscussedisexactlywhataconditionlookslike. Forthetimebeing,our
programswillusesimpleconditionsthatcomparethevaluesoftwoexpressions.
<expr> <relop> > <expr>
<relop>isshortforrelationaloperator. That
'
sjustafancynameforthemathematicalconceptslike“less
than”or“equalto.”TherearesixrelationaloperatorsinPython,showninthefollowingtable.
Python
Mathematics
Meaning
Lessthan
Lessthanorequalto
Equalto
Greaterthanorequalto
Greaterthan
!
Notequalto
Noticeespeciallytheuseof
forequality.SincePythonusesthe
signtoindicateanassignmentstate-
ment,adifferentsymbolisrequiredfortheconceptofequality. AcommonmistakeinPythonprogramsis
using
inconditions,wherea
isrequired.
Conditionsmaycompareeithernumbersorstrings. Whencomparingstrings,theorderingis lexico-
graphic. Basically,thismeansthatstringsareputinalphabeticorderaccordingtotheunderlyingASCII
codes.Soallupper-caseletterscomebeforelowercaseletters(e.g.,“Bbbb”comesbefore“aaaa”,since“B”
precedes“a”).
Ishouldmentionthatconditionsareactuallyatypeofexpression, calledaBooleanexpression,after
GeorgeBoole,a19thcenturyEnglishmathematician. WhenaBooleanexpressionisevaluated,itproduces
avalueofeithertrue(theconditionholds)orfalse(itdoesnothold).InPython,conditionsreturnintvalues.
Atrueconditionproducesa1,whileafalseconditionproducesa0.Hereareafewexamples:
Add page numbers pdf - insert pages into PDF file in C#.net, ASP.NET, MVC, Ajax, WinForms, WPF
Guide C# Users to Insert (Empty) PDF Page or Pages from a Supported File Format
adding a page to a pdf; add or remove pages from pdf
Add page numbers pdf - VB.NET PDF Page Insert Library: insert pages into PDF file in vb.net, ASP.NET, MVC, Ajax, WinForms, WPF
Easy to Use VB.NET APIs to Add a New Blank Page to PDF Document
add pages to pdf in preview; add blank page to pdf
104
CHAPTER7. CONTROLSTRUCTURES,PART1
>>> 3 < 4
1
>>> 3 * 4 < 3 3 + + 4
0
>>> "hello" == = "hello"
1
>>> "hello" < < "hello"
0
>>> "Hello" < < "hello"
1
7.1.3 Example:ConditionalProgramExecution
BackinChapter1,ImentionedthatthereareseveraldifferentwaysofrunningPythonprograms. Some
Pythonmodulefilesaredesignedtoberundirectly.Theseareusuallyreferredtoas“programs”or“scripts.”
OtherPythonmodulesaredesignedprimarilytobeimportedandusedbyotherprograms,theseareoften
called“libraries.” Sometimeswewanttocreateasortofhybridmodulethatcanbeusedbothasastand-
aloneprogramandasalibrarythatcanbeimportedbyotherprograms.
Sofar,allofourprogramshavehadalineatthebottomtoinvokethemainfunction.
main()
Asyouknow,thisiswhatactuallystartsaprogramrunning.Theseprogramsaresuitableforrunningdirectly.
Inawindowingenvironment,youmightrunafileby(double-)clickingitsicon.Oryoumighttypeacommand
likepython <myfile>.py.
SincePythonevaluatesthelinesofamoduleduringtheimportprocess,ourcurrentprogramsalsorun
whentheyareimportedintoeitheraninteractivePythonsessionorintoanotherPythonprogram.Generally,
itisnicernottohavemodulesrunastheyareimported. Whentestingaprograminteractively,theusual
approachistofirstimportthemoduleandthencallitsmain(orsomeotherfunction)eachtimewewantto
runit.
Inaprogramthatcanbeeitherimported(withoutrunning)orrundirectly,thecalltomainatthebottom
mustbemadeconditional.Asimpledecisionshoulddothetrick.
if <condition>:
main()
Wejustneedtofigureoutasuitablecondition.
Wheneveramoduleisimported,Pythonsetsaspecialvariableinthemodulecalled
name
tobethe
nameoftheimportedmodule.Hereisanexampleinteractionshowingwhathappenswiththemathlibrary.
>>> import math
>>> math.__name__
'math'
Youcansee that,whenimported, the
name
variableinsidethemath moduleis assignedthestring
'math'.
However,whenPythoncodeisbeingrundirectly(notimported),Pythonsetsthevalueof
name
tobe
'
main
'.Toseethisinaction,youjustneedtostartPythonandlookatthevalue.
>>> __name__
'__main__'
So,ifamoduleisimported,thecodeinthatmodulewillseeavariablecalled
name
whosevalueisthe
nameofthemodule.Whenafileisrundirectly,thecodewillseethat
name
hasthevalue'
main
'.
Aprogramcandeterminehowitisbeingusedbyinspectingthisvariable.
Puttingthepiecestogether,wecanchangethefinallinesofourprogramstolooklikethis:
C# Create PDF Library SDK to convert PDF from other file formats
them the ability to count the page numbers of generated PDF document in C#.NET using this PDF document creating toolkit, if you need to add some text
add page numbers to pdf preview; add blank page to pdf preview
C# Word - Word Create or Build in C#.NET
also offer them the ability to count the page numbers of generated using this Word document adding control, you can add some additional Create Word From PDF.
add page numbers pdf; add page numbers to pdf files
7.2. TWO-WAYDECISIONS
105
if __name__ == = '__main__':
main()
Thisguaranteesthatmainwillautomaticallyrunwhentheprogramisinvokeddirectly,butitwillnotrun
ifthemoduleisimported.YouwillseealineofcodesimilartothisatthebottomofvirtuallyeveryPython
program.
7.2 Two-WayDecisions
Nowthatwehaveawaytoselectivelyexecutecertainstatementsinaprogramusingdecisions,it
'
stimeto
gobackandspruceupthequadraticequationsolverfromChapter3.Hereistheprogramasweleftit:
# quadratic.py
#
A program m that t computes the real roots of f a a quadratic equation.
#
Illustrates use e of the math library.
#
Note: this s program m crashes if the equation n has s no real roots.
import math
# Makes s the math library available.
def main():
print "This s program m finds the real solutions s to o a quadratic"
print
a, b, c = input("Please enter the coefficients s (a, , b, c): ")
discRoot = = math.sqrt(b b * b - 4 * a * c)
root1 = (-b b + + discRoot) / (2 * a)
root2 = (-b b - - discRoot) / (2 * a)
print
print "The e solutions s are:", root1, root2
main()
Asnotedinthecomments,thisprogramcrasheswhenitisgivencoefficientsofaquadraticequationthat
hasnorealroots. Theproblemwiththiscodeisthatwhenb
2
4acislessthan0,theprogramattemptsto
takethesquarerootofanegativenumber.Sincenegativenumbersdonothaverealroots,themathlibrary
reportsanerror.Here
'
sanexample.
>>> import quadratic
This program finds s the e real solutions to a quadratic
Please enter the e coefficients s (a, b, c): 1,2,3
Traceback (innermost t last):
File "<stdin>", , line e 1, in ?
File "quadratic.py", , line e 21, in ?
main()
File "quadratic.py", , line e 14, in main
discRoot = = math.sqrt(b b * b - 4 * a * c)
OverflowError: math h range error
Wecanuseadecisiontocheckforthissituationandmakesurethattheprogramcan
'
tcrash. Here
'
sa
firstattempt:
# quadratic2.py
import math
C# PowerPoint - PowerPoint Creating in C#.NET
file but also offer them the ability to count the page numbers of generated NET using this PowerPoint document creating toolkit, if you need to add some text
add a page to a pdf in acrobat; adding page numbers to pdf in preview
C# Word - Word Creating in C#.NET
document file but also offer them the ability to count the page numbers of generated using this Word document creating toolkit, if you need to add some text
add page to pdf without acrobat; add page numbers to pdf using preview
106
CHAPTER7. CONTROLSTRUCTURES,PART1
def main():
print "This s program m finds the real solutions s to o a quadratic\n"
a, b, c = = input("Please e enter the coefficients s (a, , b, c): ")
dicrim = b b * * b - 4 * a * c
if discrim m >= = 0:
discRoot = = math.sqrt(discrim)
root1 = (-b + discRoot) / (2 * a)
root2 = (-b - discRoot) / (2 * a)
print "\nThe solutions are:", root1, root2
Thisversionfirstcomputesthevalueofthediscriminant(b
2
4ac)andthencheckstomakesureitisnot
negative. Onlythendoestheprogramproceedtotakethesquarerootandcalculatethesolutions. . This
programwillneverattempttocallmath.sqrtwhendiscrimisnegative.
Incidently,youmightalsonoticethatIhavereplacedthebareprintstatementsfromtheoriginalversion
oftheprogramwithembeddednewlinestoputwhitespaceintheoutput; youhadn
'
tyetlearnedabout
nthe
firsttimeweencounteredthisprogram.
Unfortunately,thisupdatedversionisnotreallyacompletesolution. Studytheprogramforamoment.
Whathappenswhentheequationhasnorealroots?Accordingtothesemanticsforasimpleif,whenb*b
- 4*a*cislessthanzero,theprogramwillsimplyskipthecalculationsandgotothenextstatement.Since
thereisnonextstatement,theprogramjustquits.Here
'
swhathappensinaninteractivesession.
>>> quadratic2.main()
This program finds s the e real solutions to a quadratic
Please enter the e coefficients s (a, b, c): 1,2,3
>>>
Thisisalmostworsethanthepreviousversion,becauseitdoesnotgivetheuseranyindicationofwhat
wentwrong;itjustleavesthemhanging. Abetterprogramwouldprintamessagetellingtheuserthattheir
particularequationhasnorealsolutions.Wecouldaccomplishthisbyaddinganothersimpledecisionatthe
endoftheprogram.
if discrim < 0:
print "The e equation n has no real roots!"
Thiswillcertainlysolveourproblem,butthissolutionjustdoesn
'
tfeelright. Wehaveprogrammeda
sequenceoftwodecisions,butthetwooutcomesaremutuallyexclusive. Ifdiscrim >= = 0istruethen
discrim < 0mustbefalseandviceversa.Wehavetwoconditionsintheprogram,butthereisreallyonly
onedecisiontomake. BasedonthevalueofdiscrimTheprogramshouldeitherprintthatthereareno
realrootsoritshouldcalculateanddisplaytheroots. Thisisanexampleofatwo-waydecision. Figure7.3
illustratesthesituation.
InPython,atwo-waydecisioncanbeimplementedbyattachinganelseclauseontoanif.Theresult
iscalledanif-elsestatement.
if <condition>:
<statements>
else:
<statements>
WhenthePythoninterpreterencountersthisstructure,itwillfirstevaluatethecondition. Iftheconditionis
true,thestatementsundertheifareexecuted. Iftheconditionisfalse,thestatementsundertheelseare
executed.Ineithercase,controlthenpassestothestatementfollowingtheif-else.
Usingatwo-waydecisioninthequadraticsolveryieldsamoreelegantsolution.
VB.NET TIFF: VB.NET Sample Codes to Sort TIFF File with .NET
manipulating multi-page TIFF (Tagged Image File), PDF, Microsoft Office If you want to add barcode into a TIFF a multi-page TIFF file with page numbers using VB
adding page numbers to a pdf in preview; add page number to pdf hyperlink
C# Excel: Create and Draw Linear and 2D Barcodes on Excel Page
can also load document like PDF, TIFF, Word get the first page BasePage page = doc.GetPage REImage barcodeImage = linearBarcode.ToImage(); // add barcode image
add a page to a pdf online; adding page numbers to pdf document
7.3. MULTI-WAYDECISIONS
107
yes
no
Print "no roots"
Calculate roots
discrim < 0 ?
Figure7.3:Quadraticsolverasatwo-waydecision.
# quadratic3.py
import math
def main():
print "This s program m finds the real solutions s to o a quadratic\n"
a, b, c = = input("Please e enter the coefficients s (a, , b, c): ")
discrim = = b b * b - 4 * a * c
if discrim m < < 0:
print "\nThe equation has no real roots!"
else:
discRoot = = math.sqrt(b * b - 4 * a * c)
root1 = (-b + discRoot) / (2 * a)
root2 = (-b - discRoot) / (2 * a)
print
print "\nThe solutions are:", root1, root2
Thisprogramfitsthebillnicely.Hereisasamplesessionthatrunsthenewprogramtwice.
>>> quadratic3.main()
This program finds s the e real solutions to a quadratic
Please enter the e coefficients s (a, b, c): 1,2,3
The equation has s no o real roots!
>>> quadratic3.main()
This program finds s the e real solutions to a quadratic
Please enter the e coefficients s (a, b, c): 2,4,1
The solutions s are: : -0.292893218813 -1.70710678119
7.3 Multi-WayDecisions
Thenewestversionofthequadraticsolveriscertainlyabigimprovement,butitstillhassomequirks. Here
isanotherexamplerun.
C# Excel - Excel Creating in C#.NET
document file but also offer them the ability to count the page numbers of generated using this Excel document creating toolkit, if you need to add some text
adding pages to a pdf; add page to pdf in preview
VB.NET Image: Guide to Convert Images to Stream with DocImage SDK
Follow this guiding page to learn how to easily convert a single image or numbers of it an image processing component which can enable developers to add a wide
add and delete pages in pdf online; adding a page to a pdf in preview
108
CHAPTER7. CONTROLSTRUCTURES,PART1
>>> quadratic3.main()
This program finds s the e real solutions to a quadratic
Please enter the e coefficients s (a, b, c): 1, 2, , 1
The solutions s are: : -1.0 -1.0
Thisistechnicallycorrect;thegivencoefficientsproduceanequationthathasadoublerootat-1.However,
theoutputmightbeconfusingtosomeusers. Itlooksliketheprogramhasmistakenlyprintedthesame
numbertwice.Perhapstheprogramshouldbeabitmoreinformativetoavoidconfusion.
Thedouble-rootsituationoccurswhendiscrimisexactly0. Inthiscase,discRootisalso0,and
bothrootshavethevalue
b
2a
.Ifwewanttocatchthisspecialcase,itlookslikeourprogramactuallyneedsa
three-waydecision.Here
'
saquicksketchofthedesign.
...
Check the value e of f discrim
when < 0: : handle e the case of no roots
when = 0: : handle e the case of a double root
when > 0: : handle e the case of two distinct t roots.
Onewaytocodethisalgorithmistousetwoif-elsestatements.Thebodyofaniforelseclause
cancontainanylegalPythonstatements,includingotheriforif-elsestatements.Puttingonecompound
statementinsideofanotheriscallednesting. Here
'
safragmentofcodethatusesnestingtoachievea
three-waydecision:
if discrim < 0:
print "Equation n has s no real roots"
else:
if discrim m == = 0:
root = -b b / / (2 * a)
print "There is a double root at", root
else:
# Do stuff f for r two roots
Ifyoutracethroughthiscodecarefully,youwillseethatthereareexactlythreepossiblepaths. The
sequencingisdeterminedbythevalueofdiscrim.AflowchartofthissolutionisshowninFigure7.4.You
canseethatthetop-levelstructureisjustanif-else. (Treatthedashedboxasonebigstatement.) ) The
dashedboxcontainsthesecondif-elsenestedcomfortablyinsidetheelsepartofthetop-leveldecision.
Onceagain,wehaveaworkingsolution,buttheimplementationdoesn
'
tfeelquiteright.Wehavefinessed
athree-waydecisionbyusingtwotwo-waydecisions.Theresultingcodedoesnotreflectthetruethree-fold
decisionoftheoriginalproblem.Imagineifweneededtomakeafive-waydecisionusingthistechnique.The
if-elsestructureswouldnestfourlevelsdeep,andthePythoncodewouldmarchofftheright-handedge
ofthepage.
Thereisanotherwaytowritemulti-waydecisionsinPythonthatpreservesthesemanticsofthenested
structuresbutgivesitamoreappealinglook. Theideaistocombineanelsefollowedimmediatelybyan
ifintoasingleclausecalledanelif.
if <condition1>:
<case1 statements>
elif <condition2>:
<case2 statements>
elif <condition3>:
<case3 statements>
...
else:
<default statements>
C#: Use XImage.OCR to Recognize MICR E-13B, OCR-A, OCR-B Fonts
may need to scan and get check characters like numbers and codes. page.RecSettings. LanguagesEnabled.Add(Language.Other); page.RecSettings.OtherLanguage
add pages to pdf without acrobat; add page number to pdf online
C# Word: How to Use C# Code to Print Word Document for .NET
are also available within C# Word Printer Add-on , like pages at one paper, setting the page copy numbers to be C# Class Code to Print Certain Page(s) of Word.
add page number to pdf document; add pdf pages to word document
7.4. EXCEPTIONHANDLING
109
discrim < 0 ?
Print "no roots"
no
yes
yes
no
Do Double Root
Do Unique Roots
discrim == 0 ?
Figure7.4:Three-waydecisionforquadraticsolverusingnestedif-else.
Thisformisusedtosetoffanynumberofmutuallyexclusivecodeblocks.Pythonwillevaluateeachcondi-
tioninturnlookingforthefirstonethatistrue. Ifatrueconditionisfound,thestatementsindentedunder
thatconditionareexecuted,andcontrolpassestothenextstatementaftertheentireif-elif-else. If
noneoftheconditionsaretrue,thestatementsundertheelseareperformed.Theelseclauseisoptional;
ifomitted,itispossiblethatnoindentedstatementblockwillbeexecuted.
Usinganif-elif-elsetoshowthethree-waydecisioninourquadraticsolveryieldsanicelyfinished
program.
# quadratic4.py
import math
def main():
print "This s program m finds the real solutions s to o a quadratic\n"
a, b, c = = input("Please e enter the coefficients s (a, , b, c): ")
discrim = = b b * b - 4 * a * c
if discrim m < < 0:
print "\nThe equation has no real roots!"
elif discrim m == = 0:
root = -b / (2 * a)
print "\nThere is a double root at", root
else:
discRoot = = math.sqrt(b * b - 4 * a * c)
root1 = (-b + discRoot) / (2 * a)
root2 = (-b - discRoot) / (2 * a)
print "\nThe solutions are:", root1, root2
7.4 ExceptionHandling
Ourquadraticprogramusesdecisionstructurestoavoidtakingthesquarerootofanegativenumberand
generatingarun-timeerror.Thisisacommonpatterninmanyprograms:usingdecisionstoprotectagainst
110
CHAPTER7. CONTROLSTRUCTURES,PART1
rarebutpossibleerrors.
Inthecaseofthequadraticsolver,wecheckedthedatabeforethecalltothesqrtfunction.Sometimes
functionsthemselvescheckforpossibleerrorsandreturnaspecialvaluetoindicatethattheoperationwas
unsuccessful. Forexample, , adifferentsquarerootoperationmightreturnanegativenumber(say-1)to
indicateanerror.Sincethesquarerootsofrealnumbersarenevernegative,thisvaluecouldbeusedtosignal
thatanerrorhadoccurred.Theprogramwouldchecktheresultoftheoperationwithadecision.
discRt = otherSqrt(b*b b - - 4*a*c)
if discRt < 0:
print "No o real l roots."
else:
...
Sometimesprogramsbecomesopepperedwithdecisionstocheckforspecialcasesthatthemainalgo-
rithmforhandlingtherun-of-the-millcasesseemscompletelylost. Programminglanguagedesignershave
comeupwithmechanismsforexceptionhandlingthathelptosolvethisdesignproblem. Theideaofan
exceptionhandlingmechanismisthattheprogrammercanwritecodethatcatchesanddealswitherrorsthat
arisewhentheprogramisrunning.Ratherthanexplicitlycheckingthateachstepinthealgorithmwassuc-
cessful,aprogramwithexceptionhandlingcaninessencesay“Dothesesteps,andifanyproblemcropsup,
handleitthisway.”
We
'
renotgoingtodiscussallthedetailsofthePythonexceptionhandlingmechanismhere,butIdowant
togiveyouaconcreteexamplesoyoucanseehowexceptionhandlingworksandunderstandprogramsthat
useit. InPython,exceptionhandlingisdonewithaspecialcontrolstructurethatissimilartoadecision.
Let
'
sstartwithaspecificexampleandthentakealookatthegeneralapproach.
HereisaversionofthequadraticprogramthatusesPython
'
sexceptionmechanismtocatchpotential
errorsinthemath.sqrtfunction.
# quadratic5.py
import math
def main():
print "This s program m finds the real solutions s to o a quadratic\n"
try:
a, b, c c = = input("Please enter the coefficients s (a, , b, c): ")
discRoot = = math.sqrt(b * b - 4 * a * c)
root1 = = (-b b + discRoot) / (2 * a)
root2 = = (-b b - discRoot) / (2 * a)
print "\nThe solutions are:", root1, root2
except OverflowError:
print "\nNo real roots"
Noticethatthisisbasicallytheveryfirstversionofthequadraticprogramwiththeadditionofatry...except
aroundtheheartoftheprogram.Atrystatementhasthegeneralform:
try:
<body>
except <ErrorType>:
<handler>
WhenPythonencountersatrystatement,itattemptstoexecutethestatementsinsidethebody. Ifthese
statementsexecutewithouterror,controlthenpassestothenextstatementafterthetry...except.Ifan
erroroccurssomewhereinthebody,Pythonlooksforanexceptclausewithamatchingerrortype. Ifa
suitableexceptisfound,thehandlercodeisexecuted.
Theoriginalprogramwithouttheexception-handlingproducedthefollowingerror.
7.4. EXCEPTIONHANDLING
111
Traceback (innermost t last):
File "<stdin>", , line e 1, in ?
File "quadratic.py", , line e 13, in ?
discRoot = = math.sqrt(b b * b - 4 * a * c)
OverflowError: math h range error
Thelastlineofthiserrormessageindicatesthetypeoferrorthatwasgenerated,namelyanOverflowError.
TheupdatedversionoftheprogramprovidesanexceptclausetocatchtheOverflowError.
Hereistheerrorhandlingversioninaction:
This program finds s the e real solutions to a quadratic
Please enter the e coefficients s (a, b, c): 1,2,3
No real roots
Insteadofcrashing,theexceptionhandlercatchestheerrorandprintsamessageindicatingthattheequation
doesnothaverealroots.
Thenicethingaboutthetry...exceptstatementisthatitcanbeusedtocatchanykindoferror,even
onesthatmightbedifficulttotestfor,andhopefully,provideagracefulexit. Forexample,inthequadratic
solver,therearelotsofotherthingsthatcouldgowrongbesideshavingabadsetofcoefficients.Iftheuser
failstotypethecorrectnumberofinputs,theprogramgeneratesaValueError. Iftheuseraccidently
typesanidentifierinsteadofanumber,theprogramgeneratesaNameError. Iftheusertypesinavalid
Pythonexpressionthatproducesnon-numericresults,theprogramgeneratesaTypeError. Asingletry
statementcanhavemultipleexceptclausestocatchvariouspossibleclassesoferrors.
Here
'
sonelastversionoftheprogramdesignedtorobustlyhandleanypossibleerrorsintheinput.
# quadratic6.py
import math
def main():
print "This s program m finds the real solutions s to o a quadratic\n"
try:
a, b, c = input("Please enter the coefficients s (a, , b, c): ")
discRoot = = math.sqrt(b * b - 4 * a * c)
root1 = (-b + discRoot) / (2 * a)
root2 = (-b - discRoot) / (2 * a)
print "\nThe solutions are:", root1, root2
except OverflowError:
print "\nNo real roots"
except ValueError:
print "\nYou didn't give me three coefficients."
except NameError:
print "\nYou didn't enter three numbers"
except TypeError:
print "\nYour inputs were not all numbers"
except:
print "\nSomething went wrong, sorry!"
Themultipleexceptsaresimilartoelifs. Ifanerroroccurs, , Pythonwilltryeachexceptinturn
lookingforonethatmatchesthetypeoferror. Thebareexceptatthebottomactslikeanelseandwill
beusedifnoneoftheothersmatch.Ifthereisnodefaultatthebottomandnoneoftheexcepttypesmatch
theerror,thentheprogramcrashesandPythonreportstheerror.
Youcanseehowthetry...exceptstatementallowsustowritereallybullet-proofprograms.Whether
youneedtogotothismuchtroubledependsonthetypeofprogramthatyouarewriting.Inyourbeginning
112
CHAPTER7. CONTROLSTRUCTURES,PART1
programs,youmightnotworrytoomuchaboutbadinput;however,professionalqualitysoftwareshoulddo
whateverisfeasibletoshieldusersfromunexpectedresults.
7.5 StudyinDesign:MaxofThree
Nowthatwehavedecisionsthatcanalterthecontrolflowofaprogram,ouralgorithmsareliberatedfrom
themonotonyofstep-by-step,strictlysequentialprocessing.Thisisbothablessingandacurse.Thepositive
sideisthatwecannowdevelopmoresophisticatedalgorithms, aswedidforourquadraticsolver. . The
negativesideisthatdesigningthesemoresophisticatedalgorithmsismuchharder.Inthissection,we
'
llstep
throughthedesignofamoredifficultdecisionproblemtoillustratesomeofthechallengeandexcitementof
thedesignprocess.
Supposeweneedanalgorithmtofindthelargestofthreenumbers. Thisalgorithmcouldbepartofa
largerproblemsuchasdetermininggradesorcomputingtaxes,butwearenotinterestedinthefinaldetails,
justthecruxoftheproblem.Thatis,howcanacomputerdeterminewhichofthreeuserinputsisthelargest?
Hereisaprogramoutline.Weneedtofillinthemissingpart.
def main():
x1, x2, x3 3 = = input("Please enter three values: : ")
# missing g code e sets max to the value of the e largest
print "The e largest t value is", max
Beforereadingthefollowinganalysis,youmightwanttotryyourhandatsolvingthisproblem.
7.5.1 Strategy1:CompareEachtoAll
Obviously,thisprogrampresentsuswithadecisionproblem.Weneedasequenceofstatementsthatsetsthe
valueofmaxtothelargestofthethreeinputsx1,x2,andx3. Atfirstglance,thislookslikeathree-way
decision;weneedtoexecuteoneofthefollowingassignments.
max = x1
max = x2
max = x3
Itwouldseemwejustneedtoprefaceeachonewiththeappropriatecondition(s),sothatitisexecutedonly
inthepropersituation.
Let
'
sconsiderthefirstpossibility,thatx1isthelargest. Toseethatx1isactuallythelargest,wejust
needtocheckthatitisatleastaslargeastheothertwo.Hereisafirstattempt:
if x1 >= x2 >= = x3:
max = x1
Yourfirstconcernhereshouldbewhetherthisstatementis syntacticallycorrect. . Theconditionx1
x2
x3doesnotmatchthetemplateforconditionsshownabove.Mostcomputerlanguageswouldnot
acceptthisasavalidexpression.ItturnsoutthatPythondoesallowthiscompoundcondition, anditbehaves
exactlylikethemathematicalrelationsx1
x2
x3.Thatis,theconditionistruewhenx1isatleastaslarge
asx2andx2isatleastaslargeasx3.So,Pythonhasnoproblemwiththiscondition.
Wheneveryouwriteadecision,youshouldaskyourselftwocrucialquestions.First,whenthecondition
istrue,areyouabsolutelycertainthatexecutingthebodyofthedecisionistherightactiontotake?Inthis
case,theconditionclearlystatesthatx1isatleastaslargeasx2andx3,soassigningitsvaluetomaxshould
becorrect.Alwayspayparticularattentiontoborderlinevalues.Noticethatourconditionincludesequalas
wellasgreater. Weshouldconvinceourselvesthatthisiscorrect. Supposethatx1,x2,andx3areallthe
same;thisconditionwillreturntrue.That
'
sOKbecauseitdoesn
'
tmatterwhichwechoose,thefirstisatleast
asbigastheothers,andhence,themax.
Documents you may be interested
Documents you may be interested