Python Break Inside Function
<p>I am using Python 3.5, and I would like to use the <code>break</code> command inside a function, but I do not know how.
I would like to use something like this:</p>

<pre><code>def stopIfZero(a):
    if int(a) == 0:
        break
    else:
        print('Continue')

while True:
    stopIfZero(input('Number: '))
</code></pre>

<p>I know that I could just use this code:</p>

<pre><code>while True:
    a = int(input('Number: '))
    if a == 0:
        break
    else:
        print('Continue')
</code></pre>

<p>And if you don't care about the <code>print('Continue')</code> part, you can even do this one-liner:
<code>while a != 0: a = int(input('Number: '))</code>(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.</p>

<p>Thanks for any help.</p>

<p>The <code>break</code> keyword is meant to be used as in your loop example only and must be inside the loop's scope.</p>

<p>Update your function to return <code>True</code> or <code>False</code> only instead:</p>

<pre><code>def is_zero(value):
    if value == 0:
        return True
    return False
</code></pre>

<p>Then in your loop, simply use like this:</p>

<pre><code>while True:
    try:
        value = int(input("Enter a value (0 to exit): "))
    except ValueError:
        # user entered a non-numeric value (e.g. a letter)
        # try asking again immediately instead of crashing :)
        print('Use numbers only, please')
        continue

    if is_zero(value):
        break

    print('Good entry. Continuing...')
</code></pre>

<p>Your <code>stopIfZero</code> function is also somewhat overloaded (i.e. has more than just 1 responsibility) because it does more than just check if a value is zero or not. For example, it:</p>

<ol>
<li>converts the arguments into an <code>int</code>,</li>
<li>prints a message, and</li>
<li>is not re-usable in other parts of your program</li>
</ol>

<p>Take those reasons into consideration to improve your code.</p>

python function python-3.x break