2

I am trying to get my script to print "ERROR" if a = 0. When running the script below, if I enter a as 0 I do get the message "error" but it also executes the rest of the script.

How can I get the script to only print "ERROR" if my condition is satisfied?

def print_num(a, b, c):

    if a == 0:
        print('ERROR')   

    print(a, b, c)
2
  • 1
    Use an else for the rest of your function or simply return after printing the error message. Commented May 21, 2020 at 5:16
  • To take your question literally then just replace print('ERROR') with exit('ERROR'). It is however bad practice with errors. Commented May 21, 2020 at 5:36

4 Answers 4

4
def print_num(a, b, c):

    if a == 0:
        raise ValueError('ERROR: a must not be zero')

    print(a, b, c)
Sign up to request clarification or add additional context in comments.

Comments

2

I like visibleman's solution but it would also work with an assert which is one less line and a bit cleaner

def print_num(a, b, c):
    assert a != 0

    print(a, b, c)

2 Comments

For something that fits a simple test (like a==0), I think you are right, an assert is cleaner from a developer standpoint. Raising is a more general solution, and allows you to make the error a bit more descriptive to the end user.
Yeah I agree, I only use raise myself. Another advantage with raising is that you can raise different errors to catch whereas assert only raises an AssertError.
1
def print_num(a, b, c):

    if a == 0:
        print('ERROR')  
        return 

    print(a, b, c)

Comments

0

You could add an else to the code. Like so:

def print_num(a, b, c):

    if a == 0:
        print('ERROR')   
    else:
        print(a, b, c)

1 Comment

The OP said they want the code to halt after the error. This code will continue to run from after the if else statement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.