Jack
Jack

Reputation: 1999

Exit If Statement if returned value is not a boolean

I have a user input for a yes or no answer. I would like to construct a function in python 3 which I could pass the value like isTrue('yes') and then the function would return True and isTrue('no') would return False. I am aware that I could just use an if statement to see if the value is just yes or no, but for other reasons, I'd benefit from using a function like isTrue(). Creating the function isTrue() is very easy, but the part I am struggling with is how to handle a value that is not true, nor false, like maybe or IDK. Ideally, I'd like to have an if statement like so

if isTrue(userInput) '''Some code here that would run anther function if the value was not true or false''':
    print('Input was Ture')
else:
    print('Input was False')

Is there a way I could return a value that I could still have the same if statement structure, but detect if the value wasn't True or False without having to do something like this and somehow have it integrated with the True if statement?

if isTrue(userInput):
    print('Input was Ture')
else !isTrue(userInput):
    print('Input was False')
else:
    print('Invalid')

Upvotes: 3

Views: 499

Answers (3)

Kenny Ostrom
Kenny Ostrom

Reputation: 5871

Since you have three possible states, you really need three possible return values. You could return True, False or None, but it makes more sense to raise a ValueError. That is also helpful for logging or displaying error messages if you put a reason in the ValueError.

truthy_values = {'yes', 'y', 't', 'true', '1'}
falsey_values = {'no', 'n', 'f', 'false', '0'}

def isTrue(userInput):
    value = userInput.strip().lower()
    if value in truthy_values:
        return True
    if value in falsey_values:
        return False
    raise ValueError('isTrue could not understand ' + userInput)

Demonstrating this function in action, with an exception handler:

def evaluate_input(userInput):
    try:
        if (isTrue(userInput)):
            print ('Input was True')
        else:
            print ('Input was False')
    except ValueError as e:
        print ('Invalid input:', str(e))

evaluate_input('True')
evaluate_input('No')
evaluate_input('Potato')

Input was True
Input was False
Invalid input: isTrue could not understand Potato

Upvotes: 1

Green Cloak Guy
Green Cloak Guy

Reputation: 24691

I would approach this problem like so:

def isTrue(value):
    truthy_values = {'yes', 'true', 'True', ...}
    return value in truthy_values

def isFalse(value):
    falsey_values = {'no', 'false', 'False', ...}
    return value in falsey_values

def isBool(value):
    return isTrue(value) or isFalse(value)

The difficulty in your case is mostly that you have non-standard definitions of what counts as True or False. A basic approach would be to make sets of the values you consider truthy or falsey, and check if the given value is in them - and if it's in neither, then it's not a boolean, and you can do with that what you will. You could also expand the definitions of isTrue() and isFalse() to cover entire classes of values (e.g. if input is a list and its length is greater than 0).

In this case you can easily check whether something is True, False, Neither, or any combination thereof, with just one call:

if isTrue(userInput): ...      # input is explicitly true
if isFalse(userInput): ...     # input is explicitly false
if not isBool(userInput): ...  # input is indeterminate
if not isTrue(userInput): ...  # input is at least not true, might be indeterminate
if not isFalse(userInput): ... # input is at least not false, might be indeterminate

at which point you could just do a simple if block:

if isTrue(userInput):
    print('Input was True')
elif isFalse(userInput):
    print('Input was False')
else:
    print('Invalid Repsonse')

Upvotes: 4

Arun Gopinathan
Arun Gopinathan

Reputation: 388

in boolean there is only True or False. but in the isTrue method if you are returning None then you can do this.

if isTrue(userInput)== True:
    print('Input was Ture')
elif isTrue(userInput) == False:
    print('Input was False')
else:
    print('Invalid')

Upvotes: 2

Related Questions