Link to home
Start Free TrialLog in
Avatar of Dier Eluom
Dier Eluom

asked on

Error catching in Python

def weather():
       import sys
       raining=input('Is it raining? ')
       while True:
        try:
           x =(input("Please enter 'yes' or 'no': ")
        
       except ValueError:
        print("That was not a valid answer.  Try again...")
       if raining == 'yes':
          ask =(input('Do you have an umbrella? '))
       if raining=='no':
              print('Go outside ')
              sys.exit(0)
       if ask == 'yes':
                  print('Go outside ')
                 

                  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? ')
                     if still =='no':
                         break
       print('Go outside !')

weather()

Open in new window


I want to be able to handle incorrect responses - user should add either yes or no.  Having trouble with the syntax.
def weather():
       import sys
       raining=input('Is it raining? ')
       while True:
        try:
           x =(input("Please enter 'yes' or 'no': ")
        
       except ValueError:
        print("That was not a valid answer.  Try again...")
       if raining == 'yes':
          ask =(input('Do you have an umbrella? '))
       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? ')
                     if still =='no':
                         break
       print('Go outside 3!')

weather()

Open in new window

Avatar of gelonida
gelonida
Flag of France image

Easiest way is perhaps to create a function, that will do the job:

try: / except: Doesn't really help you here as another string than yes or now will not provoke an exception.
It would be useful for places where you try to convert a string to an integer. A ValueError would occur if you passed a srtring containing something else than digits.


Example:


def prompt(message, choices):
    while True:
        choice = input(message)
        if choice in choices:
            return choice
        print("Your input is invalid:")

Open in new window



No just replace
x =input("Please enter 'yes' or 'no': ")

Open in new window

with
x =input("Please enter 'yes' or 'no': "m ["yes", "no"])

Open in new window

Avatar of Dier Eluom
Dier Eluom

ASKER

What is "m?
Not sure what you mean by that.  Just throws error.
oops typo and forgot to change 'input' to 'prompt' (I got interrupted while writing your response and I pressed 'send' too early)


it should have been a  ","  .
('m' is next to ',' on a French keyboard)

x =prompt("Please enter 'yes' or 'no': ", ["yes", "no"])

Open in new window

Is it raining? hjjh
Traceback (most recent call last):
  File "C:\me\My Documents\Python 3.5\WeatherNewError.py", line 9, in weather
    x=prompt("Please enter 'yes' or 'no'':",["yes","no"])
NameError: name 'prompt' is not defined

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\me\My Documents\Python 3.5\WeatherNewError.py", line 32, in <module>
    weather()
  File "C:\me\My Documents\Python 3.5\WeatherNewError.py", line 10, in weather
    except valueError:
NameError: name 'valueError' is not defined
I am using Python 3.5
ASKER CERTIFIED SOLUTION
Avatar of gelonida
gelonida
Flag of France image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Awesome, thank you!