How do you catch incorrect entries? Instead of yes or no the user enters something else?

def weather():
       import sys
       raining=input('Is it raining? ').lower()
       if raining == 'yes':
          ask =(input('Do you have an umbrella? ')).lower()
       if raining=='no':
              print('Go outside 1')
              sys.exit(0)
       if ask == 'yes':
                  print('Go outside 2')



                  sys.exit(0)


       while raining == 'yes': # this will ensure, that you do not enter the loop if it's not raining
                     print('Wait until it stops.')
                     still=input('Is it still raining? ').lower()
                     if still =='no':
                         break
       print('Go outside 3!')

weather()

Dani AI

Generated

A small reusable input-validator is the simplest, most robust way to "catch incorrect entries." was right to put the prompt logic into a helper; was right to point out that whether an empty Enter counts as yes or no should be explicit. Prefer a helper that (1) loops until a valid answer, (2) returns a boolean (so calling code stays clear), (3) accepts a configurable default, and (4) does not call sys.exit() or import inside the function β€” let the caller decide what to do on exit or error.

def ask_yes_no(prompt, default=None):
    """
    Prompt until the user gives a yes/no answer.
    default: True (yes), False (no), or None (require explicit).
    Returns True for yes, False for no.
    """
    yes = {'y', 'yes'}
    no = {'n', 'no'}
    if default is True:
        hint = ' [Y/n]'
    elif default is False:
        hint = ' [y/N]'
    else:
        hint = ' [y/n]'

    while True:
        try:
            resp = input(prompt + hint + ' ').strip().lower()
        except (EOFError, KeyboardInterrupt):
            # Use the default on EOF/Ctrl-C if provided; otherwise propagate.
            if default is not None:
                return bool(default)
            raise

        if not resp:
            if default is not None:
                return bool(default)
            print("Answer must be 'yes' or 'no'.")
            continue

        if resp in yes:
            return True
        if resp in no:
            return False
        # Accept single-letter replies like 'y' or 'n'
        if resp[0] in ('y', 'n'):
            return resp[0] == 'y'

        print("Answer must be 'yes' or 'no'.")

Use it like if ask_yes_no('Is it raining?', default=False): .... Extra tips: avoid referencing variables that may not be set (the original ask scoping can raise NameError), catch EOF/KeyboardInterrupt sensibly, and keep interactive code testable by allowing an injectable input function if you later add unit tests.

Recommended Answers

All 4 Replies

You need a loop to handle the case where the answer is not yes or no. For example

def yesno(question):
    while True:
        ans = input(question + ' (Y/n) ')
        ans = ans.strip().lower()
        if ans in ('', 'y', 'yes'):
            return 'yes'
        elif ans in ('n', 'no'):
            return 'no'
        else:
            print('Please answer yes or no ...')

def weather():
    raining = yesno('Is it raining?')
    if raining == 'no':
        print('Go outside 1')
        return
    ask = yesno('Do you have an umbrella?')
    if ask == 'yes':
        print('Go outside 2')
        return
    while raining == 'yes':
        print('Wait until it stops.')
        raining = yesno('Is it still raining?')
    print('Go outside 3!')

weather()

Edit: A tip for python, configure your editor to insert 4 space caracters when you hit the tab key. The recommended indention for python code is 4 spaces.


nice code for the guy... but i notice a small bug:
if ans in ('', 'y', 'yes'): #it should be if ans in ('y', 'yes')
if not... if the only space is enter, it will count is as yes

def yesno(question):
    while True:
        ans = input(question + ' (Y/n) ')
        ans = ans.strip().lower()
        if ans in ('', 'y', 'yes'): #it should be  if ans in ('y', 'yes')
            #if not... if the only space is enter, it will count is as yes 
            return 'yes'
        elif ans in ('n', 'no'):
            return 'no'
        else:
            print('Please answer yes or no ...')

It is not an error. When a program asks for a yes/no answer, it is customary to give a default answer which applies if the user hits the enter key. I chose here to define 'yes' as the default answer (so I write Y/n instead of y/N to indicate the default answer). The function can be improved in various ways, the default answer could be a parameter, also the function could return a boolean instead of 'yes' or 'no'.

ok, Thank for the explanation

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.