Chapter 7
Control Structures, Part 1
Sofar, wehave viewedcomputerprogramsassequencesofinstructionsthatarefollowedoneafterthe
other. Sequencingisa fundamentalconceptofprogramming,butalone,it isnotsufficienttosolve every
problem. Oftenit isnecessarytoalterthesequentialflowofa programtosuittheneedsofa particular
situation. Thisisdonewithspecialstatementsknownascontrolstructures. Inthischapter, we’ll take a
lookatdecisionstructures, whicharestatementsthatallowa programtoexecutedifferentsequencesof
instructionsfordifferentcases,effectivelyallowingtheprogramto“choose”anappropriatecourseofaction.
7.1 SimpleDecisions
7.1.1 Example:TemperatureWarnings.
Let’s startbygettingthecomputertomake a simpledecision. Foraneasyexample,we’ll returntothe
CelsiustoFahrenheittemperatureconversionprogramfromChapter2.Remember, thiswaswrittenbySuzie
Programmertohelpherfigureouthow todresseachmorninginEurope.Hereis theprogramasweleftit:
convert.py
A program to convertCelsius temps to Fahrenheit
by: Suzie Programmer
def main():
celsius = input("Whatis the Celsius temperature? ")
fahrenheit = 9.0 / 5.0 * celsius+ 32
print "The temperatureis", fahrenheit, "degrees fahrenheit."
main()
Thisis a fineprogramasfarasit goes,butwewanttoenhanceit.SuzieProgrammeris nota morning
person,andeventhoughshehasa programtoconvertthetemperatures,sometimesshedoesnotpayvery
closeattentiontotheresults.Ourenhancementtotheprogramwillensurethatwhenthetemperaturesare
extreme,theprogramprintsouta suitablewarningsothatSuzietakesnotice.
Thefirststepis to fullyspecifytheenhancement.Anextremetemperatureis eitherquitehotorquitecold.
Let’s saythatany temperatureover 90 degreesFahrenheitdeservesa heatwarning,anda temperatureunder
30 degreeswarrantsa coldwarning.Withthisspecificationinmind,wecandesignanenhancedalgorithm.
Input the temperaturein degrees Celsius (call it celsius)
Calculate fahrenheitas 9/5 celsius + 32
Output fahrenheit
if fahrenheit > 90
print a heat warning
if fahrenheit < 30
print a cold warning