-1

I made this function that does a for loop and then passes a calculated variable to a formula outside of the loop. However, I would like to stop the whole code if all the conditions are not met for my function. I put a break in my for loop hoping that it would stop my whole function but it only stopped the for loop from printing the error text a bunch of times.

Is there a way that I can stop the whole code if all conditions of my function are not properly met? I'm trying to make it so that it only shows the error print if the user puts the wrong text in.

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

test

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
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
zipline86
  • 561
  • 2
  • 7
  • 21
  • 1
    With `return` you can stop the function. You can raise an exception. – Thomas Sablik Jun 19 '18 at 13:51
  • 1
    You can either do an early `return` like @ThomasSablik said. Or you can throw an exception, which will suspend all execution until it's caught/handled. Or in the extreme case, if you want the entire program to halt you can use the `exit` builtin to suspend execution (a non-zero error code conventionally represents an error). – Edward Minnix Jun 19 '18 at 13:54
  • @EdwardMinnix how would I use the built in exit? I don't know what it is and when I looked it up I couldn't figure out how to write it in my above function. – zipline86 Jun 19 '18 at 20:25
  • @ThomasSablik replacing break with return was the easiest for me to do and understand. Thanks everybody! – zipline86 Jun 19 '18 at 20:47
  • Does this answer your question? [How do I terminate a script?](https://stackoverflow.com/questions/73663/how-do-i-terminate-a-script) – Karl Knechtel Oct 13 '22 at 19:03

2 Answers2

1

I think the best way is to use exceptions. Exceptions are implemented precisely for this case of errors. An example:

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")

In this case I would create a new exception for this kind of error.

Thomas Sablik
  • 16,127
  • 7
  • 34
  • 62
0

Your best bet would be to set a one-way flag variable to indicate this, and have the program check this before finishing after the for loop.

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

Another option would be to replace the break with a return statement. Whenever a function returns, it immediately stops. In the example below, I have the function return -1 as that is the general standard for indicating errors in returned integers. You could obviously do whatever was convenient.

  • Your code has a bug. `error` is never set equal to `False` anywhere so the test `if(error == True)` will throw an error in 2 of the 3 cases. – John Coleman Oct 13 '22 at 19:10