user285372
user285372

Reputation:

True & False in a function def

I understand what the function below does, but I don't quite get the significance (or difference) between returning True and False.

Both clauses make the program exit; i.e. upon entering a positive or negative response, the Python prompt is returned, so what actually changes internally?

Also, if I were to design such a function myself, should I use True or False if I just wanted the program to return the prompt to me without actually doing anything?

def ask(prompt, retries = 4, reminder = 'Please try again!'):
    while True:
        response = input(prompt)
        if response in ('y', 'yes'):
            print('Got y or yes!')
            return True
        if response in ('n', 'no', 'nope'):
            print('Got n or no or nope!')
            return False
        retries = retries - 1
        if retries < 0:
            raise ValueError('Invalid user response!')
        print(reminder)

ask('Do you wanna quit?')

Upvotes: 4

Views: 3004

Answers (2)

Moses Koledoye
Moses Koledoye

Reputation: 78536

Since the user's answer can be one of two sides y or n, yes or no, y or nope, yes or nope, y or no in any order, the function simply maps this list of dichotomies into a simple True or False. So you can use the function as a condition to perform an action.

if ask('Are you ill?'):
    print('Go see a physician')
else:
    print('Go hiking')

Without having to re-evaluate the user's original verbose response.

This is quite consistent with the idea of ensuring a function has only one function, which in this case is to booleanise a user's response or throw an error if the response is inconsistent after a number of trials

Upvotes: 0

user2201041
user2201041

Reputation:

Functions rarely get used alone. Returning True or False here is to help the rest of your program determine what to do. For example:

if ask('Do you like cheese?'):
    order_cheese() # Some function you've previously defined

However, if your function is designed to return to the prompt, you can use sys.exit() to return a success code that calling programs (vs functions) can take advantage of.

Upvotes: 1

Related Questions