September 10th, 2013, 02:33 AM
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.
September 10th, 2013, 03:29 AM
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.
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.
def my_function(a, b, c):
m = foo(a) + c
if not bar(b):
x = foo(a) * b + c
ret = my_function(1, 2, 3)
if ret != None:
print "Function succeeded"
print "Function failed"
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