[Tutor] Control flow

Orri Ganel singingxduck at gmail.com
Fri Jan 28 22:26:03 CET 2005


Gilbert Tsang wrote:

> Hi there, I have this logic that I cannot wrap my mind it:
>
> def go_jogging():
>    # go out and jog
>    return
>
> if ( bad_weather =='y' ):
>    # 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()
>    else:
>        # program should exit now
> else:
>    go_jogging()
>  
> ####################################################
> I can't get the program to stop processing further in the middle 
> (apparently neither exit nor goto-label exist in Python, sorry for the 
> C++ mindset) so I used exception to achieve what I want. I know in 
> that 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? Thanks, Gilbert.
>
> try:
>    if ( bad_weather =='y' ):
>        b = input ( "Weather is really bad, still go out to jog?[y/n]" )
>        if b == 'y':
>            go_jogging()
>        else:
>            raise Exception( "quit" )
>    else:
>        go_jogging()
> except Exception, inst:
>    print "Program exits now"
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
Well, if its in a function you can just do return instead of  raise 
Exception("quit") since the function exits once it returns something.  
It's sort of the same as the following:

Say you have a recursive function  fact(n) which takes in a number and 
returns the factorial of that number.  One way to code this would be:

def fact(n):
    if n > 3:
       return n*fact(n-1)
    else:
       return 2*n

However, since the function 'exits' after a  return statement, it saves 
space in general to do the following:

def fact(n):
    if n > 3:
       return n*fact(n-1)
    return 2*n

Because the only way  return 2*n will be reached is if n is smaller than 
or equal to three, which is what we wanted anyway.


BTW, the way this function works is like this:  Let's say you want to 
calculate fact(10).  10 is greater than 3, so the program calculates 
10*fact(9) and so on until fact(3) is reached, at which point it will 
return 10*(9*(8*(7*(6*(5*(4*(6))))))) (6 is 2 * 3). or the factorial of 10.

I probably didn't do too good a job explaining that, and that's probably 
not the most efficient implementation (it breaks @ around fact(1000) by 
default, and around  fact(11462) when you use  
sys.setrecursionlimit(2000) (11462 is as high as it'll go on my 
machine)), so please feel free to ask questions.

HTH,
Orri


-- 
Email: singingxduck AT gmail DOT com
AIM: singingxduck
Programming Python for the fun of it.



More information about the Tutor mailing list