Python – Returning a break statement
Question:
If you call a function to check exit conditions, can you have it return a break statement? Something like:
def check():
return break
def myLoop:
while myLoop:
check()
Is there anything like this allowed? I know the syntax as written isn’t valid.
Answers:
No, it doesn’t work like that unfortunately. You would have to check the return value and then decide to break out of the loop in the caller.
while myLoop:
result = check()
if result == 'oh no':
break
Of course, depending on what you are trying to do, it may just be as simple as:
result = check()
while result != 'oh no':
result = check()
break
is a keyword but not an object so it is treated differently by the interpreter, link. Python function can only return objects or the like.
If you want to break out of a loop when deep inside functions, one way is to use an exception:
class BreakException(Exception):
pass
Raise the exception somewhere in a function:
def some_func():
raise BreakException()
And you can break out of a loop like this:
try:
while True:
some_func()
except BreakException:
pass
I do not feel this is good practice, but have seen some language using it, Scala for example link.
def check():
#define your conditions here with if..else statement
return True
def myLoop():
while True:
if check()==True: break
If you call a function to check exit conditions, can you have it return a break statement? Something like:
def check():
return break
def myLoop:
while myLoop:
check()
Is there anything like this allowed? I know the syntax as written isn’t valid.
No, it doesn’t work like that unfortunately. You would have to check the return value and then decide to break out of the loop in the caller.
while myLoop:
result = check()
if result == 'oh no':
break
Of course, depending on what you are trying to do, it may just be as simple as:
result = check()
while result != 'oh no':
result = check()
break
is a keyword but not an object so it is treated differently by the interpreter, link. Python function can only return objects or the like.
If you want to break out of a loop when deep inside functions, one way is to use an exception:
class BreakException(Exception):
pass
Raise the exception somewhere in a function:
def some_func():
raise BreakException()
And you can break out of a loop like this:
try:
while True:
some_func()
except BreakException:
pass
I do not feel this is good practice, but have seen some language using it, Scala for example link.
def check():
#define your conditions here with if..else statement
return True
def myLoop():
while True:
if check()==True: break