[Tutor] Please critique my Fraq.py
Alan Gauld
alan.gauld at blueyonder.co.uk
Sun Jul 25 13:59:26 CEST 2004
> In Frac.py I wanted to give the user a chance to quit at any prompt
(and
> have the program close smoothly), by entering a "q" or an "x". I
did
> this by the statement,
>
> if answer in ["q", "x"]:
> break
if answer in "qxQX": break
is probably neater - to my eyes anyway, certainly less storage
although thats not likely to be an issue! :-)
> The problem with this is that it only breaks out of the inner loop.
I
> have to repeat this statement in the outer loop.
>
> So I'm asking if there's a better way. Raising an exception doesn't
do
> it.
Why does raising SystemExit not do it?
In particular if you move all cleanup code - closing files etc
into a try/finally block the exception route is the preferred method.
> Is there a way (other than mine) to enable the user to quit smoothly
> when he's inside a loop which is inside a loop?
Nope, an exception is the only reliable way to jump out of nested
loops.
It could be SystemExit to quit the program or it could be a user
defined
one
class LoopExit(exception): pass
try:
while True:
while True:
try: raise LoopBreak
finally: print "Done!"
except LoopBreak:
print "I escaped!"
HTH
Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list