Myronaz
Myronaz

Reputation: 173

Is it possible to exit a function from a subfunction it calls

my question is pretty simple. Here is the concept:

from random import randrange, uniform

def match (x, y):
        if x == y:
                print("True!")
        else:
                print("False")
                return
def main():
        while True:
                match(randrange(0, 10), randrange(0, 10))
        while True:
                match(randrange(0, 10), randrange(0, 10))
        while True:
                match(randrange(0, 10), randrange(0, 10))

main()

    

As you can see, there are two functions. main() which loops through random integers until they match, and match() which the actual integers are passed into in order to be calculated, and if a false result is encountered, both loops should break. There are two problems with this code:

  1. The loop never breaks, because the return only applies to the function to whom the code is run on. My goal is to stop the main function the moment a false result is returned.
  2. It is possible to add if statements on each line that check for a False returned result. However, that would be very inefficient and not ideal at all. There must be a better way.

I should note that this is code I modeled after a problem I'm having with my actual code, which is long and can't be copy-pasted here without context. The same principle still applies though: Much like the code here, I must stop the main function from calculating further when the subfunction it calls calculates a false result.

How can I do this? My idea was to somehow stop the main function from the subfunction match(), but is this possible? If not, what options do I have?

Upvotes: 1

Views: 532

Answers (1)

okie
okie

Reputation: 881

from random import randrange, uniform

def match (x, y):
        if x == y:
                print("True!")
        else:
                print("False")
                raise Exception()
def main():
    try:
            while True:
                    match(randrange(0, 10), randrange(0, 10))
            while True:
                    match(randrange(0, 10), randrange(0, 10))
            while True:
                    match(randrange(0, 10), randrange(0, 10))
    except:
        print("exit")
main()

This may not be the answer you wanted, but I suppose it could be helpful.

By using try and except to create a scope that include all while loop, you can exit the function via raising exception.

If you want to end the function entirely (not doing try/except in function), you can simply do this:

try:
    main()
except:
    #something else

This also allow you to do it without modifying the function itself.

Upvotes: 3

Related Questions