Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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')
like image 859
Jack Avatar asked Jun 03 '26 01:06

Jack


1 Answers

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')
like image 83
Green Cloak Guy Avatar answered Jun 04 '26 15:06

Green Cloak Guy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!