中断循环后如何停止代码

时间:2018-06-19 13:41:02

标签: python-3.x

我做了一个执行for循环的函数,然后将计算出的变量传递给循环外的公式。但是,如果我的函数没有满足所有条件,我想停止整个代码。我在for循环中稍作休息,希望它可以停止我的整个函数,但它只能停止for循环多次打印错误文本。

如果没有完全满足函数的所有条件,是否可以停止整个代码?我正在尝试使其仅在用户输入错误文本时显示错误打印。

def some_function(x, activation):
"""
Arguments:
x = data
activation stored as text string: "yes" or "no"

Returns: z
"""

    for i in range(10):
        if activation == "yes":
            y = 2 * x
        elif activation == "no":
            y = 100 * x
        else:
            print("ERROR: you must choose an activation. activation types: \"yes\" or \"no\"")
            break

    z = y + 200

    return z

测试

some_function(3, "enzyme")

ERROR: you must choose an activation. activation types: "yes" or "no"

---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-41-7a8962459048> in <module>()
----> 1 some_function(3, "y")

<ipython-input-39-e16f270340d2> in some_function(x, activation)
     17             break
     18 
---> 19     z = y + 200
     20 
     21     return z

UnboundLocalError: local variable 'y' referenced before assignment

2 个答案:

答案 0 :(得分:0)

您最好的选择是设置一个单向标志变量来表明这一点,并让程序在for循环之后完成之前对其进行检查。

def some_function(x, activation):
"""
Arguments:
x = data
activation stored as text string: "yes" or "no"

Returns: z
"""

for i in range(10):
    if activation == "yes":
        y = 2 * x
    elif activation == "no":
        y = 100 * x
    else:
        print("ERROR: you must choose an activation. activation types: \"yes\" or     \"no\"")
        error = True
        break

if(error == True):

    z = y + 200
    return z

另一个选择是将break替换为return语句。每当函数返回时,它都会立即停止。在下面的示例中,我具有函数return -1,因为这是指示返回的整数中的错误的通用标准。您显然可以做任何方便的事情。

答案 1 :(得分:0)

我认为最好的方法是使用异常。正是针对这种情况的错误实现了异常。例子:

class ActivationException(Exception):
    pass

def some_function(x, activation):
    """
    Arguments:
    x = data
    activation stored as text string: "yes" or "no"

    Returns: z
    """

    for i in range(10):
        if activation == "yes":
            y = 2 * x
        elif activation == "no":
            y = 100 * x
        else:
            raise ActivationException

    z = y + 200

    return z

try:
    some_function(1, '')
except ActivationException:
    print("ERROR: you must choose an activation. activation types: \"yes\" or \"no\"")
except:
    print("ERROR: unexpected error")

在这种情况下,我将为这种错误创建一个新的异常。