[Tutor] Please critique my Fraq.py
Dick Moores
rdm at rcblue.com
Sun Jul 25 14:23:18 CEST 2004
At 04:59 7/25/2004, Alan Gauld wrote:
> > 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
I'm happy to learn another way. I suppose I could do this with all types
of sequences.
>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.
How about Brian van den Broek's suggestion of about an hour ago, of using
sys.exit(). That does what I was after, if I execute at the XP command
line. With IDLE, it doesn't.
> > 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.
Could you explain what you mean by reliable? For the problem I posed, one
answer is to use sys.exit().
>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!"
I'll give your suggestion a try, but I don't understand classes yet.
Thanks very much,
Dick
More information about the Tutor
mailing list