Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Break Inside Function [duplicate]

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.

like image 397
nedla2004 Avatar asked Sep 20 '16 19:09

nedla2004


1 Answers

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
like image 52
JCOC611 Avatar answered Oct 05 '22 23:10

JCOC611