sarbjit
sarbjit

Reputation: 3894

Preventing python definition from execution

I want to know what is the best way of checking an condition in Python definition and prevent it from further execution if condition is not satisfied. Right now i am following the below mentioned scheme but it actually prints the whole trace stack. I want it to print only an error message and do not execute the rest of code. Is there any other cleaner solution for doing it.

def Mydef(n1,n2):
    if (n1>n2):
        raise ValueError("Arg1 should be less than Arg2)
    # Some Code


Mydef(2,1)

Upvotes: 2

Views: 164

Answers (2)

Umur Kontacı
Umur Kontacı

Reputation: 35478

def Mydef(n1,n2):
    if (n1>n2):
        print "Arg1 should be less than Arg2"
        return None
    # Some Code


Mydef(2,1)

Functions stop executing when they reach to return statement or they run the until the end of definition. You should read about flow control in general (not specifically to python)

Upvotes: 0

Rostyslav Dzinko
Rostyslav Dzinko

Reputation: 40795

That is what exceptions are created for. Your scheme of raising exception is good in general; you just need to add some code to catch it and process it

try:
    Mydef(2,1)
except ValueError, e:
    # Do some stuff when exception is raised, e.message will contain your message

In this case, execution of Mydef stops when it encounters raise ValueError line of code, and goes to the code block under except.

You can read more about exceptions processing in the documentation.

If you don't want to deal with exceptions processing, you can gracefully stop function to execute further code with return statement.

def Mydef(n1,n2):
    if (n1>n2):
        return

Upvotes: 2

Related Questions