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()

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.

@Gribouillis
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 ...')

@jnneson 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.