Dave
Dave

Reputation: 4328

what return value is used to show method has succeeded or failed in python

What is the correct way to show an operation has failed in python. In this code what should the return values be?

def compare(y,x):
     if y ==  x:
         return 'true'
     return 'false'

Upvotes: 0

Views: 1040

Answers (3)

Russell Borogove
Russell Borogove

Reputation: 19037

Your compare() example is problematic for this question for two reasons:

  • You'd normally just use a bare == to get a boolean comparison result in Python, rather than calling a function.
  • Neither result here is "succeeded" or "failed", so they don't really address the title question.

In Python, it's common for functions to indicate success or failure not by a return value but rather by assuming that they succeeded unless they raise an exception. Exceptions are preferable to return indications for three reasons:

  • They're harder to accidentally ignore.
  • They don't require you to reserve a return value that would otherwise be valid.
  • They can be handled directly at the most convenient point in the call tree without having to explicitly pass an error value up through several function returns.

Here's a more Pythonic example:

def doThing(x,low,high):        
    """
    Do a thing if x is between the low and high values, inclusive. 
    If x is out of bounds, the thing fails.
    """
    if x < low or x > high:
         raise ValueError( "x is out of bounds" )
    return (x-low)/(high-low)

Upvotes: 3

Blckknght
Blckknght

Reputation: 104712

Python has literal values True and False which you can use. However, it's rarely necessary to use them explicitly, as comparison operations will return one or the other value in most cases. For instance, you could redo your function to be:

def compare(y, x):
    return y == x

It's also worth noting that non-Boolean values can be considered "true" or "false", if necessary. The "falsy" values are None, 0 and all empty containers (such as the empty string '', the empty list [], the empty tuple (), the empty dictionary {} and so on). Everything else is "truthy" by default, including all instances of most kinds of objects.

Custom classes can have a boolean conversion defined by implementing the magical method __nonzero__ (which is renamed to __bool__ in Python 3). If it doesn't exist, Python will check for __len__, and if that doesn't exist give up and assume all instances are true.

Upvotes: 5

Nihathrael
Nihathrael

Reputation: 515

def compare(y,x):
     if y == x:
         return True
     return False

or implicit:

def compare(y,x):
    return x == y

Here is a more detailed introduction the python boolean type: http://docs.python.org/release/2.3.5/whatsnew/section-bool.html

Upvotes: 3

Related Questions