#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Location
    California, USA
    Posts
    76
    Rep Power
    2

    Exit a busy function if conditions not met


    Is there a method to leave a lengthy function? I'm curious to
    know if there is an alternative to nested if statements. When
    certain conditions required by the function are not met at the
    beginning or along the way, it would be handy to be able to
    immediately stop further execution of the function.
    Python version is 3.3. Thanks.
  2. #2
  3. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,612
    Rep Power
    4247
    You could always use the return keyword to hop out early. Just make the return statement return an out-of-bounds value so that the caller knows that the function exited prematurely.
    Code:
    def my_function(a, b, c):
       if foo(a):
            m = foo(a) + c
            if not bar(b):
                return None
            x = foo(a) * b + c
            return x
        else:
            return None
    
    ret = my_function(1, 2, 3)
    if ret != None:
        print "Function succeeded"
    else:
        print "Function failed"
    Here, the function my_function() returns some number if it succeeds or None if it fails. Then the caller can simply check if my_function returns a number or not, to decide if it succeeded. The nice thing is that you can return None at any point of my_function(), even deep inside several nested blocks.
    Up the Irons
    What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home.
    "Death Before Dishonour, my Friends!!" - Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest
    Down with Sharon Osbourne

    "I wouldn't hire a butcher to fix my car. I also wouldn't hire a marketing firm to build my website." - Nilpo

IMN logo majestic logo threadwatch logo seochat tools logo