Search code examples
pythonloops

Python - Returning a break statement


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.


Solution

  • 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()