[Tutor] Control flow

Alan Gauld alan.gauld at freenet.co.uk
Fri Jan 28 23:09:54 CET 2005


SEveral solutions here.

The best is to restructure the code a little:

> def go_jogging():
>     # go out and jog
>     return
>
> if not bad_weather == 'y':  # where is this initially set BTW?
    go_jogging()
  else
>     # ask user only if weather is bad.
>     b = input ( "Weather is really bad, still go out to jog?[y/n]" )
>     if b == 'y':
>        go_jogging()

Its shorter, simpler and makes the most common case the default
(assuming that bad weather is the exception!)

> I can't get the program to stop processing further in the middle

Good, that would be really bad practice from a structured programming
point of view. :-)
But if you really, really must, you could always call

raise SystemExit

which bombs out more or less immediately - like exit() in C....

> C++ mindset) so I used exception to achieve what I want.

Yes thats ok, and the exception to use is already there...

> example you could probably manipulate the logic so that program ends
at
> the bottom of the if-tree. My question is then how to exit in the
middle
> of a if-then-else tree?

You should never need to. One of the things that structured
programming
(Edsgar Dijkstra to be precise) showed was that you can *always*
rearrange
things so that goto's and intermediate exits are not needed and indeed
can introduce an extra level of complexity and error.

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