Control of flow
Tom Good
Tom_Good1 at excite.com
Wed Aug 1 14:50:58 EDT 2001
Campbell <cb921 at voice.co.za> wrote in message news:<Pine.LNX.4.31.0107311355450.2321-100000 at cb921.local>...
> Hi,
>
> I use python to write telephony apps, and I find that a 'goto' is often
> a nice tool (stop going 'aargh', its properly "useful" sometimes =).
>
> Here is a little snippet that gets a month/day from a caller. If the
> day entered is not in the range of days valid for the month entered, we
> repeat from the top. Does anyone have a few minutes to waste helping
> me?? How better can I code things that look like this:
>
> >>> snip <<<
> while 1:
> cont = 1 ## ugh!
> month = getdtmf("enter2digs.vox", 2)
> if month < 1 or month > 12:
> play("invalidmonth.vox")
> continue
> while 1:
> day = getdtmf("enterday", 2)
> if day < 1 or day > Month[month]:
> play("invalidday.vox")
> cont = 1
> cont = 0
> if cont == 1:
> continue
> break
> >>> snip <<<
Here's a quick example of the kind of thing you might do instead. I
have NOT tested this code -- when I write pseudocode, I write it in
Python ;-)
This shows an approach using functions and exceptions instead of loop
control variables.
class startOverException(Exception):
pass
def someMainFunction():
# . . .
month, day = getMonthAndDay()
# . . .
def getMonthAndDay():
while 1:
try:
month = getmonth()
day = getday(month)
return (month, day)
except startOverException:
pass # try again from the top
def getmonth():
while 1:
month = getdtmf("enter2digs.vox")
if month < 1 or month >12:
play("invalidmonth.vox")
else:
return month
def getday(month):
while 1:
day = getdtmf("enterday", 2)
if day < 1:
play("invalidday.vox") # re-enter day
elif day > Month[month]:
play("invalidday.vox")
raise startOverException # start over, re-enter month
else:
return day # day was OK
More information about the Python-list
mailing list