Python Break Inside Function

31,938

Solution 1

Usually, this is done by returning some value that lets you decide whether or not you want to stop the while loop (i.e. whether some condition is true or false):

def stopIfZero(a):
    if int(a) == 0:
        return True
    else:
        print('Continue')
        return False

while True:
    if stopIfZero(input('Number: ')):
        break

Solution 2

A function can't break on behalf of its caller. The break has to be syntactically inside the loop.

Solution 3

You want to use return, not break.

break is used to stop a loop.

The break statement, like in C, breaks out of the smallest enclosing for or while loop.

return is used to exit the function and return a value. You can also return None.

Share:
31,938
nedla2004
Author by

nedla2004

I like to program with Python 3, which causes endless problems with old modules! I want to learn other languages, but not just yet.

Updated on September 21, 2020

Comments

  • nedla2004
    nedla2004 over 3 years

    I am using Python 3.5, and I would like to use the break command inside a function, but I do not know how. I would like to use something like this:

    def stopIfZero(a):
        if int(a) == 0:
            break
        else:
            print('Continue')
    
    while True:
        stopIfZero(input('Number: '))
    

    I know that I could just use this code:

    while True:
        a = int(input('Number: '))
        if a == 0:
            break
        else:
            print('Continue')
    

    And if you don't care about the print('Continue') part, you can even do this one-liner: while a != 0: a = int(input('Number: '))(as long as a was already assigned to something other than 0) However, I would like to use a function, because other times it could help a lot.

    Thanks for any help.