Reputation: 173
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:
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
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