python if statement satisfied, don't continue script

Viewed 666

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)
4 Answers
def print_num(a, b, c):

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

    print(a, b, c)

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)
def print_num(a, b, c):

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

    print(a, b, c)

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